[Python爬虫之路2]爬取百度贴吧内容

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_28057541/article/details/55510688
# 目标:
# 1. 对百度贴吧的任意帖子进行抓取
# 2. 指定是否只抓取楼主的发帖内容

# 分析url可知url分为两个部分,基础部分,参数部分

__author__ = 'XZ'
# -*- coding:utf-8 -*-
# 使得python支持中文

import requests
from bs4 import BeautifulSoup
import re

class BDTB:
    # 初始化,传入基础部分和参数部分(参数部分决定是否只看楼主)
    def __init__(self):
        self.base = None
        self.seeL = None

    # 从一个帖子中获取信息
    def getTieInfo(self, tie):
        # 发帖人,内容(非图片),时间,楼数
        name = tie.find('li',class_ = "d_name").text
        content = tie.find('div',class_ = "d_post_content").text
        wrap = tie.find('div',class_='post-tail-wrap').contents
        time = wrap[2].text
        floor = wrap[1].text
        print(name)
        print(time)
        print(content)
        print(floor)
        print(u"-------------------------------------------------------------------------------------------"
              u"------------------------------------\n")

    # 获取一个单页,参数为我们要获取的帖子页码数
    def getApage(self,pageIndex):
        try:
            url = self.base + '?see_lz=' + str(self.seeL) + '&pn=' + str(pageIndex)
            reponse = requests.get(url).content
            soup = BeautifulSoup(reponse,'html.parser')
            ties = soup.find_all('div',class_ = re.compile("l_post l_post_bright j_l_post clearfix"))
            for tie in ties:
                self.getTieInfo(tie)
        except requests.HTTPError as e:
            print(e+"在获取贴吧内容时出现错误!")

    # 获取一共有多少页
    def getPageNumber(self):
        try:
            url = self.base + '?see_lz=' + str(self.seeL) + '&pn=1'
            reponse = requests.get(url).content
            soup = BeautifulSoup(reponse,'html.parser')
            number = soup.find('li',class_ = "l_reply_num").contents[2].text
            return number
        except requests.HTTPError as e:
            print(e+"在获取贴吧页码时出现错误!")
            return None;

    # 开始运行
    def start(self):
        # 输入贴子代号
        self.base = input("请输入帖子代号:")
        # 输入是否只看群主
        self.seeL = input("输入1表示只看群主,0表示浏览所有帖子:")
        # 先获取有页码数n
        pageNumber = int(self.getPageNumber())
        # 然后每次按下enter:获取当前页,并解析出内容,如果到了最后一页,则无法继续,提示已经是最后一页
        print("按Enter刷新下一页,输入Q退出!")
        for e in range(1,pageNumber):
            i = input()
            if i == 'Q' or i == 'q':
                print("退出程序!")
                break
            self.getApage(e)
        else:
            print("全部帖子以展示完,退出程序!")

# 使用BDTB

baseURL = 'http://tieba.baidu.com/p/3138733512'
bdtb = BDTB()
bdtb.start() #获取第一页的内容

class 的多值解析

关于bs4的class搜索:

虽然class是多至属性,但是是有写法要求的:

css_soup = BeautifulSoup('<p class="body strikeout"></p>')

一开始我尝试用 find_all('div',class_="a b c") 来搜索,结果搜索列表为空,因为bs4把“a b c”当作一个字符串来解析了

猜你喜欢

转载自blog.csdn.net/qq_28057541/article/details/55510688
今日推荐