用Python爬取百度贴吧帖子

作者: 1想得美 | 来源:发表于2017-08-23 18:22 被阅读182次

一、介绍

前前后后拖了很久的一个爬虫纯原创我心中的NBA2014-2015赛季现役50大,一般的抓取信息还是蛮简单的,但这个爬虫在于有些楼层是含图片的,这样我们抓取下来就会有<img.*?>之类的东西,很难受;还有就是这个爬虫告诉我们当正则走投无路时BeautifulSoup或许是个不错的选择,在匹配数据的时候很好用

二、流程

  • 目标站点分析
    用浏览器打开纯原创我心中的NBA2014-2015赛季现役50大,开始审查元素,没什么特别的,很基础的网页结构,但在抓取楼层号和时间的我们发现问题了——我(艹皿艹 )这让我怎么写正则,还有天理吗???
    1.0
2.0
  • 客官莫慌,我们有标签选择器
    标签选择器的写法也有很多种,我这里是参考大邓的写法,还蛮好理解的

  • 开启循环,批量抓取

  • 保存数据至文本

三、代码

import requests
from requests.exceptions import RequestException
import re
import json
from bs4 import BeautifulSoup   #都是基本的几个库

def get_one_page(url):
    try:
        response=requests.get(url)
        if response.status_code == 200:
            return response.text
        return None
    except RequestException:
        return None

def get_the_number():
    a = input("是否只获取楼主发言,是输入1,否输入0:")
    a = int(a)
    if a == 1 or a == 0:
        if a == 1:
            print("只看楼主模式>>>")
            write_to_file("只看楼主模式>>>")
        else:
            print('普通模式>>>')
            write_to_file("普通模式>>>")   #这部分我还是比较满意的
    pattern = re.compile('<h3 class="core_title_txt.*?>(.*?)</h3>.*?'
                         +'<span class="red".*?>(.*?)</span>.*?<span '
                          +'class="red">(.*?)</span>.*?</div>', re.S)   #为了匹配准确我把正则写的不那么“正则”
    html=requests.get('https://tieba.baidu.com/p/3138733512?see_lz='+str(a)).text
    result=re.search(pattern,str(html))
    if result:
        print('标题:', result.group(1))
        print('回复数:',result.group(2))
        b= result.group(3)
        print('页数:',b)
    else:
        print('获取页数信息失败')
    return a,b   #return多个对象,没毛病

def get_the_floor_time(html):   #把楼层号和时间的信息搞出来
    soup = BeautifulSoup(html, 'lxml')
    items=soup.find_all('span',{'class':'tail-info'})   #嗯,这里就用标签选择器来选择楼层号和时间
    pattern = re.compile('<span class="tail-info">(\d.*?)</span>', re.S)   #再用正则匹配,这个时候一定要细心,一开始我写的是'<span class="tail-info">(\d.*?)</span>,'结果最后一个日期就匹配不到,具体原因看items,仔细看!
    items = re.findall(pattern, str(items))
    return items   #这里得到的items是一个列表,返回它就好,之后再输出

def get_the_content(html):   #输出帖子的楼层内容并且把<img....>之类的删了
    soup = BeautifulSoup(html, 'lxml')
    contents=soup.find_all('div',{'class':'d_post_content j_d_post_content '})
    if contents:
        items=get_the_floor_time(html)
        i=-1
        for content in contents:
            content=content.get_text().strip()   #得到楼层内容的纯文本
            i=i+1
            print(items[2 * i])
            write_to_file(items[2 * i])   #写入数据
            print(items[2 * i + 1])
            write_to_file(items[2 * i + 1])
            print(content)
            write_to_file(content)
            print('----------------------------------------------------------------------------------------------------')
            write_to_file('-------------------------------------------------------------------------------------------')
    else:
        print("获取帖子内容失败")

def write_to_file(content):   #这基本是标配了
    with open('bdtb_result.text','a',encoding='utf-8') as f:
        f.write(json.dumps(content,ensure_ascii=False)+'\n')
        f.close()

def main():
    c = get_the_number()   #得到的是get_the_number()的返回值,一个列表
    a=(c[0])
    b=int(c[1])   #这里要int,b代表的是页数,得到b,我们就知道要循环多少次了
    for b in range(1,b+1):
        url = 'https://tieba.baidu.com/p/3138733512?see_lz='+str(a)+'&pn='+str(b)
        get_one_page(url)
        html=get_one_page(url)
        get_the_content(html)
        
if __name__=='__main__':
        main()

四、最后得到的数据视图和文件

3.0

五、总结

1.要好好利用工具,遇到问题多问度娘
2.在这里最初的想法是把每个楼层的用户名也打印出来的,运行到300多层的时候总是报错,等我找到好的解决办法再po上来
3.未完待续.....

相关文章

  • 用Python爬取百度贴吧帖子

    一、介绍 前前后后拖了很久的一个爬虫纯原创我心中的NBA2014-2015赛季现役50大,一般的抓取信息还是蛮简单...

  • 爬取百度贴吧帖子

    依然是参考教程 Python爬虫实战一之爬取百度贴吧帖子。作者崔庆才写了很多关于Python爬虫的文章,大家有兴趣...

  • 可视化pyecharts库初体验

    爬取学校贴吧150个帖子,统计词频,简单数据分析 一、数据采集目标站点:百度贴吧 二、分词统计词频(jieba) ...

  • python爬取百度贴吧

    爬取百度贴吧python文件源代码如下(欢迎点赞哦) import urllib.request import u...

  • python爬取百度贴吧

    爬取百度贴吧python文件源代码如下(欢迎点赞哦) import urllib.request import u...

  • python爬虫-抓取百度贴吧帖子图片

    本爬虫可以爬取百度贴吧帖子中的图片,代码有待完善,欢迎大家指教!出处:https://github.com/jin...

  • Python爬虫实战

    注:采转归档,自己学习查询使用 Python爬虫实战(1):爬取糗事百科段子Python爬虫实战(2):百度贴吧帖...

  • python爬取百度贴吧的图片1

    python版本:2.7.10学习python爬虫,首先写了一个爬取百度贴吧图片的程序。参考了静觅的系列博客 好了...

  • python爬取百度贴吧

    1.对百度贴吧的任意帖子进行抓取 2.指定是否只抓取楼主发帖内容 3.将抓取到的内容分析并保存到文件

  • python爬虫之百度贴吧

    最近又尝试着爬取了百度贴吧,发现新增的几个反爬点,故来做下记录。 爬取百度贴吧大致流程为: 1 - 构造url,h...

网友评论

    本文标题:用Python爬取百度贴吧帖子

    本文链接:https://www.haomeiwen.com/subject/dtrrdxtx.html