Python爬蟲(chóng)爬取新聞資訊案例詳解
前言
本文的文字及圖片來(lái)源于網(wǎng)絡(luò),僅供學(xué)習(xí)、交流使用,不具有任何商業(yè)用途,版權(quán)歸原作者所有,如有問(wè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í)有所幫助,也希望大家多多支持腳本之家。
- 利用python爬取斗魚(yú)app中照片方法實(shí)例
- Python爬蟲(chóng)實(shí)例——爬取美團(tuán)美食數(shù)據(jù)
- Python爬蟲(chóng)爬取百度搜索內(nèi)容代碼實(shí)例
- Python爬蟲(chóng)爬取電影票房數(shù)據(jù)及圖表展示操作示例
- Python爬蟲(chóng)爬取煎蛋網(wǎng)圖片代碼實(shí)例
- python爬蟲(chóng)爬取筆趣網(wǎng)小說(shuō)網(wǎng)站過(guò)程圖解
- Python爬蟲(chóng)實(shí)現(xiàn)的根據(jù)分類(lèi)爬取豆瓣電影信息功能示例
- Python爬蟲(chóng)之爬取淘女郎照片示例詳解
相關(guān)文章
使用python對(duì)多個(gè)txt文件中的數(shù)據(jù)進(jìn)行篩選的方法
今天小編就為大家分享一篇使用python對(duì)多個(gè)txt文件中的數(shù)據(jù)進(jìn)行篩選的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-07-07
Pycharm編輯器技巧之自動(dòng)導(dǎo)入模塊詳解
我們?cè)诰幊踢^(guò)程中經(jīng)常會(huì)不經(jīng)意的使用到一些尚未導(dǎo)入的類(lèi)和模塊,在這種情況下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)技巧之去除列表中的空值元素,搜集針對(duì)python高效處理數(shù)據(jù)的核心代碼,今天是實(shí)現(xiàn)去除列表中的空值元素,需要的朋友可以參考下2023-02-02
利用python實(shí)現(xiàn)JSON文檔與Python對(duì)象互相轉(zhuǎn)換
這篇文章主要介紹了利用python實(shí)現(xiàn)JSON文檔與Python對(duì)象互相轉(zhuǎn)換,通過(guò)對(duì)將一個(gè)JSON文檔映射為Python對(duì)象問(wèn)題的展開(kāi)介紹主題內(nèi)容,需要的朋友可以參考一下2022-06-06
Python3.9 beta2版本發(fā)布了,看看這7個(gè)新的PEP都是什么
這篇文章主要介紹了Python3.9 beta2版本發(fā)布了,看看這7個(gè)新的PEP都是什么,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2020-06-06
python3+telnetlib實(shí)現(xiàn)簡(jiǎn)單自動(dòng)測(cè)試示例詳解
telnetlib 模塊提供一個(gè)實(shí)現(xiàn)Telnet協(xié)議的類(lèi) Telnet,本文重點(diǎn)給大家介紹python3+telnetlib實(shí)現(xiàn)簡(jiǎn)單自動(dòng)測(cè)試示例詳解,需要的朋友可以參考下2021-08-08
詳解如何用Flask中的Blueprints構(gòu)建大型Web應(yīng)用
Blueprints是Flask中的一種模式,用于將應(yīng)用程序分解為可重用的模塊,這篇文章主要為大家詳細(xì)介紹了如何使用Blueprints構(gòu)建大型Web應(yīng)用,需要的可以參考下2024-03-03

