Python爬蟲爬取新聞資訊案例詳解
前言
本文的文字及圖片來源于網(wǎng)絡(luò),僅供學(xué)習(xí)、交流使用,不具有任何商業(yè)用途,版權(quán)歸原作者所有,如有問題請及時(shí)聯(lián)系我們以作處理。
一個(gè)簡單的Python資訊采集案例,列表頁到詳情頁,到數(shù)據(jù)保存,保存為txt文檔,網(wǎng)站網(wǎng)頁結(jié)構(gòu)算是比較規(guī)整,簡單清晰明了,資訊新聞內(nèi)容的采集和保存!

應(yīng)用到的庫
requests,time,re,UserAgent,etree
import requests,time,re
from fake_useragent import UserAgent
from lxml import etree
列表頁面

列表頁,鏈接xpath解析
href_list=req.xpath('//ul[@class="news-list"]/li/a/@href')
詳情頁


內(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)
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
使用python對多個(gè)txt文件中的數(shù)據(jù)進(jìn)行篩選的方法
今天小編就為大家分享一篇使用python對多個(gè)txt文件中的數(shù)據(jù)進(jìn)行篩選的方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-07-07
Pycharm編輯器技巧之自動(dòng)導(dǎo)入模塊詳解
我們在編程過程中經(jīng)常會(huì)不經(jīng)意的使用到一些尚未導(dǎo)入的類和模塊,在這種情況下Pycharm會(huì)幫助我們定位模塊文件位置并將其添加到導(dǎo)入列表中,這也就是所謂的自動(dòng)導(dǎo)入模塊功能。本文給大家介紹了關(guān)于Pycharm編輯器技巧之自動(dòng)導(dǎo)入模塊的相關(guān)資料,需要的朋友可以參考下。2017-07-07
python去除列表中的空值元素實(shí)戰(zhàn)技巧
這篇文章主要介紹了python實(shí)戰(zhàn)技巧之去除列表中的空值元素,搜集針對python高效處理數(shù)據(jù)的核心代碼,今天是實(shí)現(xiàn)去除列表中的空值元素,需要的朋友可以參考下2023-02-02
利用python實(shí)現(xiàn)JSON文檔與Python對象互相轉(zhuǎn)換
這篇文章主要介紹了利用python實(shí)現(xiàn)JSON文檔與Python對象互相轉(zhuǎn)換,通過對將一個(gè)JSON文檔映射為Python對象問題的展開介紹主題內(nèi)容,需要的朋友可以參考一下2022-06-06
Python3.9 beta2版本發(fā)布了,看看這7個(gè)新的PEP都是什么
這篇文章主要介紹了Python3.9 beta2版本發(fā)布了,看看這7個(gè)新的PEP都是什么,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2020-06-06
python3+telnetlib實(shí)現(xiàn)簡單自動(dòng)測試示例詳解
telnetlib 模塊提供一個(gè)實(shí)現(xiàn)Telnet協(xié)議的類 Telnet,本文重點(diǎn)給大家介紹python3+telnetlib實(shí)現(xiàn)簡單自動(dòng)測試示例詳解,需要的朋友可以參考下2021-08-08
詳解如何用Flask中的Blueprints構(gòu)建大型Web應(yīng)用
Blueprints是Flask中的一種模式,用于將應(yīng)用程序分解為可重用的模塊,這篇文章主要為大家詳細(xì)介紹了如何使用Blueprints構(gòu)建大型Web應(yīng)用,需要的可以參考下2024-03-03

