1.爬虫基本步骤
2.requests模块
3.parsel模块
4.xpath数据解析方法
5.分页功能
1.获取网页地址 (糗事百科的段子的地址)
2.发送请求
3.数据解析
4.保存 本地
import re import requests import parsel1.获取网页地址
url = 'https://www.qiushibaike.com/text/'
# 请求头 伪装客户端向服务器发送请求
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'
}
2.发送请求
requ = requests.get(url=url, headers=headers).text3.数据解析
sel = parsel.Selector(requ) # 解析对象4.保存数据href = sel.xpath('//body/div/div/div[2]/div/a[1]/@href').getall() for html in href: txt_href = 'https://www.qiushibaike.com' + 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[@]/text()').getall() content = sel2.xpath('//body/div[2]/div/div[2]/div[2]/div[1]/div/text()').getall() contents = 'n'.join(content)
with open('糗事百科text\'+title + '.txt', mode='w', encoding='utf-8') as fp:
fp.write(contents)
print(title, '下载成功')
运行代码,得到数据
【付费VIP完整版】只要看了就能学会的教程,80集Python基础入门视频教学
点这里即可免费在线观看


