Python爬蟲(chóng)實(shí)戰(zhàn)演練之采集糗事百科段子數(shù)據(jù)
知識(shí)點(diǎn)
1.爬蟲(chóng)基本步驟
2.requests模塊
3.parsel模塊
4.xpath數(shù)據(jù)解析方法
5.分頁(yè)功能
爬蟲(chóng)基本步驟:
1.獲取網(wǎng)頁(yè)地址 (糗事百科的段子的地址)
2.發(fā)送請(qǐng)求
3.數(shù)據(jù)解析
4.保存 本地
爬蟲(chóng)代碼
導(dǎo)入所需模塊
import re import requests import parsel
獲取網(wǎng)頁(yè)地址
url = 'https://www.qiushibaike.com/text/'
# 請(qǐng)求頭偽裝客戶(hù)端向服務(wù)器發(fā)送請(qǐng)求
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36'
}
發(fā)送請(qǐng)求
requ = requests.get(url=url, headers=headers).text
數(shù)據(jù)解析
sel = parsel.Selector(requ) # 解析對(duì)象 <Selector xpath=None data='<html xmlns="http://www.w3.org/1999/x...'>
href = sel.xpath('//body/div/div/div[2]/div/a[1]/@href').getall()
for html in href:
txt_ + html
requ2 = requests.get(url=txt_href, headers=headers).text
sel2 = parsel.Selector(requ2)
title = sel2.xpath('//body/div[2]/div/div[2]/h1/text()').get().strip()
title = re.sub(r'[|/\:?<>*]','_',title)
# content = sel2.xpath('//div[@class="content"]/text()').getall()
content = sel2.xpath('//body/div[2]/div/div[2]/div[2]/div[1]/div/text()').getall()
contents = '\n'.join(content)
保存數(shù)據(jù)
with open('糗事百科text\\'+title + '.txt', mode='w', encoding='utf-8') as fp:
fp.write(contents)
print(title, '下載成功')
運(yùn)行代碼,得到數(shù)據(jù)


【付費(fèi)VIP完整版】只要看了就能學(xué)會(huì)的教程,80集Python基礎(chǔ)入門(mén)視頻教學(xué)
點(diǎn)這里即可免費(fèi)在線觀看
到此這篇關(guān)于Python爬蟲(chóng)實(shí)戰(zhàn)演練之采集糗事百科段子數(shù)據(jù)的文章就介紹到這了,更多相關(guān)Python 采集糗事百科段子內(nèi)容請(qǐng)搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來(lái)源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來(lái)源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來(lái)源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來(lái),僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。
關(guān)注官方微信