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

演示效果

糗事百科

相关推荐
前端 贾公子18 小时前
v-if 与 v-for 的优先级对比
开发语言·前端·javascript
嗯嗯=20 小时前
python学习篇
开发语言·python·学习
WoY202020 小时前
opencv-python在ubuntu系统中缺少依赖
python·opencv·ubuntu
大游小游之老游1 天前
Python中如何实现一个程序运行时,调用另一文件中的函数
python
mantch1 天前
个人 LLM 接口服务项目:一个简洁的 AI 入口
人工智能·python·llm
不会c嘎嘎1 天前
QT中的常用控件 (二)
开发语言·qt
weixin_445054721 天前
力扣热题51
c++·python·算法·leetcode
是一个Bug1 天前
50道核心JVM面试题
java·开发语言·面试
朱朱没烦恼yeye1 天前
java基础学习
java·python·学习
她和夏天一样热1 天前
【观后感】Java线程池实现原理及其在美团业务中的实践
java·开发语言·jvm