Python爬虫(十七)_糗事百科案例

糗事百科实例

爬取糗事百科段子,假设页面的URL是: http://www.qiushibaike.com/8hr/page/1

要求:

  1. 使用requests获取页面信息,用XPath/re做数据提取
  2. 获取每个帖子里的用户头像连接、用户姓名、段子内容、点赞次数和评论次数
  3. 保存到json文件内

参考代码

javascript 复制代码
#-*- coding:utf-8 -*-

import requests
from lxml import etree

page = 1
url = 'http://www.qiushibaike.com/8hr/page/' + str(page) 
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36',
    'Accept-Language': 'zh-CN,zh;q=0.8'}

try:
    response = requests.get(url, headers=headers)
    resHtml = response.text

    html = etree.HTML(resHtml)
    result = html.xpath('//div[contains(@id,"qiushi_tag")]')

    for site in result:
        item = {}

        imgUrl = site.xpath('./div//img/@src')[0].encode('utf-8')

        # print(imgUrl)
        username = site.xpath('./div//h2')[0].text
        # print(username)
        content = site.xpath('.//div[@class="content"]/span')[0].text.strip().encode('utf-8')
        # print(content)
        # 投票次数
        vote = site.xpath('.//i')[0].text
        # print(vote)
        #print site.xpath('.//*[@class="number"]')[0].text
        # 评论信息
        comments = site.xpath('.//i')[1].text
        # print(comments)
        print imgUrl, username, content, vote, comments

except Exception, e:
    print e

演示效果

糗事百科

相关推荐
论文复现现场6 小时前
本地 PyTorch 训练 OOM,第一次租 RTX 4090 云 GPU 怎么迁移项目?从环境检查到 100 Step 跑通
人工智能·pytorch·python·深度学习·cuda
云雀衔光6 小时前
MCP 协议全景:为什么它是 AI 连接工具的「USB-C」
java·开发语言·数据库·人工智能·ai编程
geovindu6 小时前
go: Task Scheduler
开发语言·后端·golang
会飞的拖把7 小时前
Python 多任务编程:并发、进程、线程与线程安全详解
开发语言·python
君顾17 小时前
折扣卡 CPS 小程序定制:从业务流程到系统架构的实践指南
java·开发语言·折扣卡
2601_956319887 小时前
看到“2026年量化学习”时,交易想法要先拆成条件和动作
人工智能·python
老猿讲编程7 小时前
【Eclipse OpenSOVD学习之六】 数据访问层(DataProvider)
学习·eclipse·嵌入式软件·车载·sovd
大模型码小白8 小时前
Harness Engineering 驾驭工程:从使用到项目实战
大数据·数据库·人工智能·python·spring
浔溺8 小时前
al+大数据每日学习笔记36
大数据·笔记·学习
坚定学代码8 小时前
static在c++中的使用
开发语言·c++