[Python爬虫之路2]爬取百度贴吧内容
来源:互联网 发布:手机淘宝昵称怎么修改 编辑:程序博客网 时间:2024/05/20 07:16
# 目标:# 1. 对百度贴吧的任意帖子进行抓取# 2. 指定是否只抓取楼主的发帖内容# 分析url可知url分为两个部分,基础部分,参数部分__author__ = 'XZ'# -*- coding:utf-8 -*-# 使得python支持中文import requestsfrom bs4 import BeautifulSoupimport reclass 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("全部帖子以展示完,退出程序!")# 使用BDTBbaseURL = '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”当作一个字符串来解析了
0 0
- [Python爬虫之路2]爬取百度贴吧内容
- python爬虫入门:2--爬取百度贴吧内容
- Python爬虫实战之爬取百度贴吧帖子
- Python 爬虫 多线程爬取百度贴吧内容,并将内容存到本地
- python爬虫之爬取百度音乐
- python爬虫之爬取百度音乐
- Python爬虫爬取百度百科内容实例
- python学习笔记之爬虫之爬取百度贴吧某一帖子
- Python简单爬虫,爬取百度贴吧
- python爬虫爬取百度贴吧的信息
- Python爬虫爬取百度贴吧多线程版
- python爬虫小项目: 爬取百度贴吧帖子
- python爬虫小项目:爬取百度贴吧图片
- python爬虫(13)爬取百度贴吧帖子
- Python爬虫实例--爬取百度贴吧小说
- Python爬虫实战二之爬取百度贴吧帖子
- Python爬虫urllib笔记(四)之使用BeautifulSoup爬取百度贴吧
- Python爬虫实战二之爬取百度贴吧帖子
- Spring Boot 数据响应之数据加密以及字段过滤
- linux kernel 编译内核模块代码,插入内核模块遇到的问题和解决
- 同步类CyclicBarrier整理
- 爱油科技基于SpringCloud的微服务实践
- c++调用win32API控制打印机打印
- [Python爬虫之路2]爬取百度贴吧内容
- 解决openwrt刷上后没有无线,art也刷了
- HDU2054_A==B?_字符串处理
- Hibernate中关于持久化类的三种状态
- sql 查出一张表中重复的所有记录数据
- 数据库——游标
- 网站统计中的数据收集原理及实现(有说前端如何埋点)
- JAVA动态代理模拟
- 队列和栈