前言
本文的文字及图片来源于网络,仅供学习、交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理。
一个简单的Python资讯采集案例,列表页到详情页,到数据保存,保存为txt文档,网站网页结构算是比较规整,简单清晰明了,资讯新闻内容的采集和保存!
应用到的库
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')
详情页
内容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()')
内容格式化处理
detail='\n'.join(details)
标题格式化处理,替换非法字符
pattern = r"[\/\\\:\*\"\<\>\|]"
new_title = re.sub(pattern, "_", title) # 替换为下划线
保存数据,保存为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文本成功!")
遍历数据采集,yield处理
def get_tasks(self):
data_list = self.parse_home_list(self.url)
for item in data_list:
yield item
程序运行效果
程序采集效果
附源码参考:
# -*- 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(">采集出错需延时,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)
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
更新日志
- 丁红《女儿情》[DTS-WAV]
- 陈惠婷.2017-Voyager3【亚神音乐】【FLAC分轨】
- 群星.2001-华纳歌声魅影【华纳】【WAV+CUE】
- 张雨生.2016-雨后星空2CD【丰华】【WAV+CUE】
- 李雨寰《Break Free》[FLAC/分轨][533MB]
- 廖也欧《面朝大海》[320K/MP3][18.35MB]
- 廖也欧《面朝大海》[Hi-Res][24bit 48kHz][FLAC/分轨][170.14MB]
- s13T1夺冠五人名单都有谁 s13T1夺冠五人名单一览
- 英雄联盟T1战队队长都有谁 T1战队所有队长介绍
- skt历届战队成员都有哪些 skt历届战队成员名单盘点
- 妙音唱片《大热唱片3》[WAV+CUE]
- 费玉清《跟着地球旋转》滚石时代经典复刻[正版原抓WAV+CUE]
- 罗文甄妮-射雕英雄传(AMCD)(限量版)[WAV+CUE]
- 《巫师4》定档2025再添佐证:参演人员曝光 老将回归
- 辣眼睛 美女COS《黑神话:悟空》比基尼版金池长老