那么既然上一篇文字里的問題解決了,下面就來把爬蟲代碼貼在這里,供日后回顧用破喻。
另外,上一篇提到的覆蓋問題曼尊,最終在網(wǎng)上找到的解決辦法如下:
原第16行:csv_file =open('data.csv', 'w', encoding="utf-8", newline='')
改成:csv_file =open('data.csv', 'a', encoding="utf-8", newline='')
差別是:w 改成了 a
原理如下:python利用open打開文件的方式:
w:以寫方式打開酬诀,?
a:以追加模式打開 (從 EOF 開始, 必要時(shí)創(chuàng)建新文件)?
r+:以讀寫模式打開?
w+:以讀寫模式打開 (參見 w )?
a+:以讀寫模式打開 (參見 a )?
rb:以二進(jìn)制讀模式打開?
wb:以二進(jìn)制寫模式打開 (參見 w )?
ab:以二進(jìn)制追加模式打開 (參見 a )?
rb+:以二進(jìn)制讀寫模式打開 (參見 r+ )?
wb+:以二進(jìn)制讀寫模式打開 (參見 w+ )?
ab+:以二進(jìn)制讀寫模式打開 (參見 a+ )
資料來源:https://blog.csdn.net/lwgkzl/article/details/82147474
下面是代碼:
import requests
import csv
from bs4import BeautifulSoup
for jin range(100):#爬取前多少頁的新聞就填幾
? ? j+=1
? ? if j ==1:
html = requests.get("http://web.fosu.edu.cn/news/category/school-news")
else:
html = requests.get("http://web.fosu.edu.cn/news/category/school-news"+"/page/"+str(j))
soup = BeautifulSoup(html.content, 'lxml')#初始化,由于html是request對(duì)象骆撇,無法用beautifulsoup解釋瞒御,因此在后面加上.contain
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? #print(soup)輸出soup轉(zhuǎn)換后的內(nèi)容
? ? all_news = soup.find('div', class_="contain2_right_bottom")#找到最大的div,其class為contain2_big
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? #print(all_news) #輸出新聞盒子div里的內(nèi)容
? ? csv_file =open('data.csv', 'a', encoding="utf-8", newline='')#''
? ? writer = csv.writer(csv_file)
writer.writerow(["新聞標(biāo)題","發(fā)布時(shí)間","新聞鏈接","新聞內(nèi)容"])#寫入標(biāo)題
? ? print('正在爬第' +str(j) +'頁新聞')
for iin range(10):#爬取目錄第一頁的新聞標(biāo)題及鏈接
? ? ? ? all_a_tag = all_news.find_all('a')# 找到所有的a標(biāo)簽神郊,賦值給all_a_tag
? ? ? ? news_name = all_a_tag[i].text#標(biāo)題的抓取
? ? ? ? news_link = all_a_tag[i]['href']#鏈接的抓取
? ? ? ? # 新聞?wù)牡淖ト?/p>
? ? ? ? html_a = requests.get(news_link)
soup_a = BeautifulSoup(html_a.content, 'lxml')
news_contain = soup_a.find('div', class_='contain3_right_bottom')
news_main = news_contain.text
#新聞發(fā)布時(shí)間的抓取
? ? ? ? news_time = soup_a.find('div', class_='contain3_right_bottom_xx')
news_time_a = news_time.text
print('新聞標(biāo)題:{}肴裙,時(shí)間:{},鏈接:{}涌乳,內(nèi)容:{}'.format(news_name,news_time_a,news_link,news_main))
writer.writerow([news_name,news_time_a,news_link,news_main])
print('第' +str(j) +'頁第'+str(i+1) +'篇新聞爬取完畢蜻懦!')
print('第' +str(j) +'頁新聞爬取完畢!')
csv_file.close()
print("寫入完畢夕晓!")