【Python爬虫】糗事百科数据段子采集

知识点

1.爬虫基本步骤
2.requests模块
3.parsel模块
4.xpath数据解析方法
5.分页功能

爬虫基本步骤:

1.获取网页地址 (糗事百科的段子的地址)
2.发送请求
3.数据解析
4.保存 本地

爬虫代码

导入所需模块

import re
import requests
import parsel

1.获取网页地址

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).text

3.数据解析

sel = parsel.Selector(requ)  # 解析对象
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[@class="content"]/text()').getall()
    content = sel2.xpath('//body/div[2]/div/div[2]/div[2]/div[1]/div/text()').getall()
    contents = '\n'.join(content)

4.保存数据

with open('糗事百科text\\'+title + '.txt', mode='w', encoding='utf-8') as fp:
    fp.write(contents)
    print(title, '下载成功')

运行代码,得到数据

Original: https://www.cnblogs.com/qshhl/p/15430257.html
Author: 松鼠爱吃饼干
Title: 【Python爬虫】糗事百科数据段子采集

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/511064/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球