爬取百度贴吧的帖子

要解析下面的 HTML, 提取到 div 中的文本:

<div id="post_content_91765531755" class="d_post_content j_d_post_content  clearfix">            楼主现在iOS10么</div>

定位到 @id 以 post_content 开头并且 @class为 d_post_content j_d_post_content clearfix 的 div。

>>> import lxml
>> html = requests.get('http://tieba.baidu.com/p/4609646212')
>>> content = etree.HTML(html.text)
>>> content = content.xpath('//div[starts-with(@id, "post_content") and contains(@class,"d_post_content j_d_post_content  clearfix")]')
  • starts-with(@attr, "xxxx") 函数, 以 xxxx 开头的 attr 属性。
  • contains(@attr, "xxxx") 函数, 精确含有值为 xxxx 的属性。
  • and, 两个函数都为真时, 则返回过滤后的元素。

爬取百度贴吧里面的帖子, 爬取字段为 「回帖日期」、「回帖人」、「回帖内容」:

# -*- coding:utf-8 -*-

from lxml import etree
from multiprocessing.dummy import Pool as ThreadPool
import requests
import json

def spider(url):
    # test_url = 'http://tieba.baidu.com/p/4609646212'
    html = requests.get(url)
    selector = etree.HTML(html.text)
    # 获取每个内容块
    content_field = selector.xpath('//div[@class="l_post j_l_post l_post_bright  "]')
    reply = {}
    for each_content in content_field:
        reply_info = json.loads(each_content.xpath('@data-field')[0])
        author = reply_info['author']['user_name']
        reply_time = reply_info['content']['date']
        content = each_content.xpath('div[@class="d_post_content_main"]/div/cc/div[starts-with(@id, "post_content") \
                                        and contains(@class,"d_post_content j_d_post_content  clearfix")]')
        #content = each_content.xpath('div[@class="d_post_content_main"]/div/cc/div[@class="d_post_content j_d_post_content  clearfix"]')
        print(author)
        print(reply_time)
        print(content[0].xpath('string(.)').replace(' ', ''))
        print('----------------------------------------------------')
        reply['reply_author'] = author
        reply['reply_content_time'] = reply_time
        reply['reply_content'] = content[0].xpath('string(.)').replace(' ', '')
        savetofile(reply)


def savetofile(dict):
    f.writelines(u'回帖时间:' + str(dict['reply_content_time']) + "\n")
    f.writelines(u'回贴人:'   + dict['reply_author'] + "\n")
    f.writelines(u'回帖内容:' + dict['reply_content'] + "\n")
    f.writelines("\n\n")


if __name__ == '__main__':
    pool = ThreadPool(4) # 使用 4 核 cpu
    page = []
    base_url = 'http://tieba.baidu.com/p/4609646212?pn='
    f = open("result.txt", "a", encoding='utf-8') # 将结果写入文件

    [page.append(base_url + str(i)) for i in range(1, 21)]

    result = pool.map(spider, page)
    pool.close()
    pool.join()
    f.close()

注意, 元素的定位一定要精确, 不然会发生报错。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1.JQuery 基础 改变web开发人员创造搞交互性界面的方式。设计者无需花费时间纠缠JS复杂的高级特性。 1....
    LaBaby_阅读 1,394评论 0 2
  • 1.JQuery 基础 改变web开发人员创造搞交互性界面的方式。设计者无需花费时间纠缠JS复杂的高级特性。 1....
    LaBaby_阅读 1,203评论 0 1
  • 问答题47 /72 常见浏览器兼容性问题与解决方案? 参考答案 (1)浏览器兼容问题一:不同浏览器的标签默认的外补...
    _Yfling阅读 13,826评论 1 92
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,067评论 19 139
  • 第一章 入门 基本功能:访问和操作 dom 元素,控制页面样式,对页面的事件处理,与ajax完美结合,有丰富的插件...
    X_Arts阅读 1,069评论 0 2