例子:本文使用requests、xpath庫(kù)模擬爬取糗事百科的段子內(nèi)容。
導(dǎo)入爬蟲時(shí)所用的庫(kù)
import requests #導(dǎo)入requests 庫(kù)
from lxml import etree # 導(dǎo)入lxml
建立user-agent(用戶代理):,模擬瀏覽器訪問(wèn)。
headers = {'user-agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.163 Safari/535.1'}
單頁(yè)數(shù)據(jù)爬取和多頁(yè)數(shù)據(jù)爬取
#爬取單頁(yè)內(nèi)容
url='https://www.qiushibaike.com/hot/'
r= requests.get(url,headers=headers,timeout=20).text #使用get方法獲取數(shù)據(jù),timeout:設(shè)置設(shè)定秒數(shù)結(jié)束之后停止等待響應(yīng)
s= etree.HTML(r)
xiaohua=s.xpath('//a[1]/div/span/text()')
#爬取多頁(yè)內(nèi)容
for page in range(9):#定義頁(yè)數(shù)為9。
r=requests.get('https://www.qiushibaike.com/hot/page/{}/'.format(page),headers=headers,timeout=100).text
s= etree.HTML(r)
xiaohua=s.xpath('//a[1]/div/span/text()')
爬取后導(dǎo)入txt文件中
with open ('xiaohua.txt','w',encoding='utf-8')as f:
for i in xiaohao:
f1.write(i)
爬取后導(dǎo)入到CSV文件中
import pandas as pd #導(dǎo)入pandas庫(kù)
b1=pd.DataFrame(xiaohua)#需將list內(nèi)容先轉(zhuǎn)化為DataFrame類型
b1.to_csv('xiaohua.csv')
本文僅做學(xué)習(xí)專用,未做商業(yè)活動(dòng),如有侵權(quán),請(qǐng)聯(lián)系刪除