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

演示效果

糗事百科

相关推荐
故事和你913 分钟前
sdut-python-实验四-python序列结构(21-27)
大数据·开发语言·数据结构·python·算法
SuperEugene8 分钟前
TypeScript+Vue 实战:告别 any 滥用,统一接口 / Props / 表单类型,实现类型安全|编码语法规范篇
开发语言·前端·javascript·vue.js·安全·typescript
chushiyunen10 分钟前
pycharm注意力残差示例
ide·python·pycharm
liuyao_xianhui11 分钟前
优选算法_模拟_提莫攻击_C++
开发语言·c++·算法·动态规划·哈希算法·散列表
2301_7938046919 分钟前
用Python和Twilio构建短信通知系统
jvm·数据库·python
B站_计算机毕业设计之家21 分钟前
计算机毕业设计:Python当当网图书数据全链路处理平台 Django框架 爬虫 Pandas 可视化 大数据 大模型 书籍(建议收藏)✅
爬虫·python·机器学习·django·flask·pandas·课程设计
不要秃头的小孩29 分钟前
力扣刷题——111.二叉树的最小深度
数据结构·python·算法·leetcode
.select.30 分钟前
c++ 移动赋值/移动构造函数
开发语言·c++
我是鶸41 分钟前
secml-malware python library 源码分析及实践
开发语言·python
red_redemption44 分钟前
自由学习记录(141)
学习