欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > python >内容正文

python

python爬取贴吧所有标题的评论_用BS4爬取贴吧文章的作者信息时,如何兼顾爬取高亮的作者信息?...

发布时间:2025/3/19 python 63 豆豆
生活随笔 收集整理的这篇文章主要介绍了 python爬取贴吧所有标题的评论_用BS4爬取贴吧文章的作者信息时,如何兼顾爬取高亮的作者信息?... 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

百度贴吧上的文章信息中,一般的作者信息代码,如下所示:

别让依靠成

而有部分作者信息是橙色的。如下所示:

冰缘瑞雪...

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

"""

获取百度贴吧:生活大爆炸吧的基本内容

爬虫线路:requests - bs4

Python版本:3.5

1. 从网上爬下特定页码的网页

2. 对于爬下的页面内容进行简单的筛选分析

3. 找到每一篇帖子的 标题、发帖人、日期、楼层、以及跳转链接

4. 将结果保存到文本

"""

import requests

import time

from bs4 import BeautifulSoup

# 抓取网页的函数

def get_html(url):

try:

r = requests.get(url, timeout=30)

# 判断网络连接状态,出现错误时抛出异常

r.raise_for_status()

# r.encoding = r.apparent_encoding.

r.encoding = 'utf-8'

return r.text

except:

return '网络连接异常'

# 分析贴吧的网页文件,整理信息,保存在列表变量中

def get_content(url):

# 保存所有帖子信息

comments = []

# 获取网址

html = get_html(url)

# 熬汤

soup = BeautifulSoup(html, 'lxml')

# 获取li标签的列表

liTags = soup.find_all('li', attrs={'class': ' j_thread_list clearfix'})

# 遍历帖子中需要的信息

for li in liTags:

# 保存文章信息到字典

comment = {}

# 当爬虫找不到信息时抛出异常

try:

# 保存信息到字典

comment['title'] = li.find('a', attrs={'class': 'j_th_tit '})['title']

comment['link'] = "http://tieba.baidu.com/" + \

li.find('a', attrs={'class': 'j_th_tit '})['href']

comment['name'] = li.find('a', attrs={'class': 'frs-author-name j_user_card '}).string

comment['time'] = li.find('span', attrs={'class': 'pull-right is_show_create_time'}).string

comment['replyNum'] = li.find(

'span', attrs={'class': 'threadlist_rep_num center_text'}).string

comments.append(comment)

except:

print('找不到相关文章信息')

return comments

# 将结果保存到本地

def Out2File(dict):

# 打开文件,使用追加模式

with open('D:\BDTB.txt', 'a+', encoding='utf-8') as f:

for comment in dict:

f.write('标题: {} \t 链接:{} \t 发帖人:{} \t 发帖时间:{} \t 回复数量: {} \n'.format(

comment['title'], comment['link'], comment['name'], comment['time'], comment['replyNum']))

print('当前页面爬取完成')

def main(base_url, deep):

url_list = []

# 将需要爬取的url存入列表

for i in range(0, deep):

url_list.append(base_url + '&pn=' + str(50 * i))

print('所有网址下载完毕,开始筛选信息...')

# 遍历分析所有数据,并保存到本地

for url in url_list:

content = get_content(url)

Out2File(content)

print('所有文章信息保存完毕!')

base_url = 'http://tieba.baidu.com/f?ie=utf-8&kw=%E7%94%9F%E6%B4%BB%E5%A4%A7%E7%88%86%E7%82%B8&fr=search'

# 设置需要爬取的页码数量

deep = 3

if __name__ == '__main__':

main(base_url, deep)

总结

以上是生活随笔为你收集整理的python爬取贴吧所有标题的评论_用BS4爬取贴吧文章的作者信息时,如何兼顾爬取高亮的作者信息?...的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。