Python爬蟲爬取新聞資訊案例詳解
前言
本文的文字及圖片來(lái)源于網(wǎng)絡(luò),僅供學(xué)習(xí)、交流使用,不具有任何商業(yè)用途,版權(quán)歸原作者所有,如有問題請(qǐng)及時(shí)聯(lián)系我們以作處理。
一個(gè)簡(jiǎn)單的Python資訊采集案例,列表頁(yè)到詳情頁(yè),到數(shù)據(jù)保存,保存為txt文檔,網(wǎng)站網(wǎng)頁(yè)結(jié)構(gòu)算是比較規(guī)整,簡(jiǎn)單清晰明了,資訊新聞內(nèi)容的采集和保存!
應(yīng)用到的庫(kù)
requests,time,re,UserAgent,etree
import requests,time,re
from fake_useragent import UserAgent
from lxml import etree
列表頁(yè)面
列表頁(yè),鏈接xpath解析
href_list=req.xpath('//ul[@class="news-list"]/li/a/@href')
詳情頁(yè)
內(nèi)容xpath解析
h2=req.xpath('//div[@class="title-box"]/h2/text()')[0]
author=req.xpath('//div[@class="title-box"]/span[@class="news-from"]/text()')[0]
details=req.xpath('//div[@class="content-l detail"]/p/text()')
內(nèi)容格式化處理
detail='\n'.join(details)
標(biāo)題格式化處理,替換非法字符
pattern = r"[\/\\\:\*\?\"\<\>\|]"
new_title = re.sub(pattern, "_", title) # 替換為下劃線
保存數(shù)據(jù),保存為txt文本
def save(self,h2, author, detail):
with open(f'{h2}.txt','w',encoding='utf-8') as f:
f.write('%s%s%s%s%s'%(h2,'\n',detail,'\n',author))print(f"保存{h2}.txt文本成功!")
遍歷數(shù)據(jù)采集,yield處理
def get_tasks(self):
data_list = self.parse_home_list(self.url)
for item in data_list:
yield item
程序運(yùn)行效果
程序采集效果
附源碼參考:
# -*- coding: UTF-8 -*- import requests,time,re from fake_useragent import UserAgent from lxml import etree class RandomHeaders(object): ua=UserAgent() @property def random_headers(self): return { 'User-Agent': self.ua.random, } class Spider(RandomHeaders): def __init__(self,url): self.url=url def parse_home_list(self,url): response=requests.get(url,headers=self.random_headers).content.decode('utf-8') req=etree.HTML(response) href_list=req.xpath('//ul[@class="news-list"]/li/a/@href') print(href_list) for href in href_list: item = self.parse_detail(f'https://yz.chsi.com.cn{href}') yield item def parse_detail(self,url): print(f">>正在爬取{url}") try: response = requests.get(url, headers=self.random_headers).content.decode('utf-8') time.sleep(2) except Exception as e: print(e.args) self.parse_detail(url) else: req = etree.HTML(response) try: h2=req.xpath('//div[@class="title-box"]/h2/text()')[0] h2=self.validate_title(h2) author=req.xpath('//div[@class="title-box"]/span[@class="news-from"]/text()')[0] details=req.xpath('//div[@class="content-l detail"]/p/text()') detail='\n'.join(details) print(h2, author, detail) self.save(h2, author, detail) return h2, author, detail except IndexError: print(">>>采集出錯(cuò)需延時(shí),5s后重試..") time.sleep(5) self.parse_detail(url) @staticmethod def validate_title(title): pattern = r"[\/\\\:\*\?\"\<\>\|]" new_title = re.sub(pattern, "_", title) # 替換為下劃線 return new_title def save(self,h2, author, detail): with open(f'{h2}.txt','w',encoding='utf-8') as f: f.write('%s%s%s%s%s'%(h2,'\n',detail,'\n',author)) print(f"保存{h2}.txt文本成功!") def get_tasks(self): data_list = self.parse_home_list(self.url) for item in data_list: yield item if __name__=="__main__": url="https://yz.chsi.com.cn/kyzx/jyxd/" spider=Spider(url) for data in spider.get_tasks(): print(data)
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python3.x檢查內(nèi)存可用大小的兩種實(shí)現(xiàn)
本文將介紹如何使用Python 3實(shí)現(xiàn)檢查L(zhǎng)inux服務(wù)器內(nèi)存可用大小的方法,包括使用Python標(biāo)準(zhǔn)庫(kù)實(shí)現(xiàn)和使用Linux命令實(shí)現(xiàn)兩種方式,感興趣可以了解一下2023-05-05python的print輸出在控制臺(tái)并且將輸出內(nèi)容保存為文件(最新推薦)
這篇文章主要介紹了python的print輸出在控制臺(tái)并且將輸出內(nèi)容保存為文件,我感覺就是類似于重寫一下調(diào)用print的時(shí)候執(zhí)行的方法,讓他既能夠在控制臺(tái)輸出,也能保存到文件里去,需要的朋友可以參考下2023-01-01Pandas刪除數(shù)據(jù)的幾種情況(小結(jié))
這篇文章主要介紹了Pandas刪除數(shù)據(jù)的幾種情況(小結(jié)),詳細(xì)的介紹了4種方式,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-06-06Python學(xué)習(xí)筆記之open()函數(shù)打開文件路徑報(bào)錯(cuò)問題
這篇文章主要介紹了Python學(xué)習(xí)筆記之open()函數(shù)打開文件路徑報(bào)錯(cuò)問題,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來(lái)看看吧2018-04-04