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

演示效果

糗事百科

相关推荐
tang7778911 小时前
爬虫代理报错速查:407/408/409/410/503 从报错到根治(实测可用)
爬虫·爬虫代理·动态代理ip·代理ip·503·407·爬虫报错
DLYSB_12 小时前
API 网关流量洪峰与突发 CC 攻击:我用 Go 写了个“现场物理防御哨兵”,把故障响应压缩到秒级
开发语言·后端·golang·报警灯
山荷枝13 小时前
Java学习第十天
java·学习
huibin14785236913 小时前
热缓解学习记录
android·学习
matlabgoodboy13 小时前
计算机毕设代做|Java Python Matlab APP 全套开发设计
java·python·课程设计
雨田言炎13 小时前
四、关于Qt项目需要知道的
开发语言·笔记·qt
用户83562907805114 小时前
Python Word 转 PDF 和 PDF 转 Word 指南
后端·python
猿长大人14 小时前
C# | JSON 序列化中的多态接口处理:基于 Attribute 实现精准 $type 控制
c#·json
用户83562907805114 小时前
如何使用 Python 加密和保护 Word 文档
后端·python
Fluxproxy14 小时前
AI数据集采集、批量模型推理报错频发?AI项目网络稳定性优化实战
python·ai·ai编程