Python爬蟲實戰(zhàn)演練之采集糗事百科段子數(shù)據(jù)
發(fā)布日期:2021-12-21 21:28 | 文章來源:CSDN
知識點
1.爬蟲基本步驟
2.requests模塊
3.parsel模塊
4.xpath數(shù)據(jù)解析方法
5.分頁功能
爬蟲基本步驟:
1.獲取網(wǎng)頁地址 (糗事百科的段子的地址)
2.發(fā)送請求
3.數(shù)據(jù)解析
4.保存 本地
爬蟲代碼
導入所需模塊
import re import requests import parsel
獲取網(wǎng)頁地址
url = 'https://www.qiushibaike.com/text/' # 請求頭偽裝客戶端向服務器發(fā)送請求 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ā)送請求
requ = requests.get(url=url, headers=headers).text
數(shù)據(jù)解析
sel = parsel.Selector(requ) # 解析對象 <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, '下載成功')
運行代碼,得到數(shù)據(jù)
【付費VIP完整版】只要看了就能學會的教程,80集Python基礎入門視頻教學
點這里即可免費在線觀看
到此這篇關于Python爬蟲實戰(zhàn)演練之采集糗事百科段子數(shù)據(jù)的文章就介紹到這了,更多相關Python 采集糗事百科段子內(nèi)容請搜索本站以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持本站!
版權聲明:本站文章來源標注為YINGSOO的內(nèi)容版權均為本站所有,歡迎引用、轉載,請保持原文完整并注明來源及原文鏈接。禁止復制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務器上建立鏡像,否則將依法追究法律責任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學習參考,不代表本站立場,如有內(nèi)容涉嫌侵權,請聯(lián)系alex-e#qq.com處理。
相關文章