python爬取贴吧所有标题的评论_用BS4爬取贴吧文章的作者信息时,如何兼顾爬取高亮的作者信息?...
百度貼吧上的文章信息中,一般的作者信息代碼,如下所示:
別讓依靠成
而有部分作者信息是橙色的。如下所示:
冰緣瑞雪...
# -*-coding:utf-8-*-
"""
獲取百度貼吧:生活大爆炸吧的基本內(nèi)容
爬蟲線路:requests - bs4
Python版本:3.5
1. 從網(wǎng)上爬下特定頁(yè)碼的網(wǎng)頁(yè)
2. 對(duì)于爬下的頁(yè)面內(nèi)容進(jìn)行簡(jiǎn)單的篩選分析
3. 找到每一篇帖子的 標(biāo)題、發(fā)帖人、日期、樓層、以及跳轉(zhuǎn)鏈接
4. 將結(jié)果保存到文本
"""
import requests
import time
from bs4 import BeautifulSoup
# 抓取網(wǎng)頁(yè)的函數(shù)
def get_html(url):
try:
r = requests.get(url, timeout=30)
# 判斷網(wǎng)絡(luò)連接狀態(tài),出現(xiàn)錯(cuò)誤時(shí)拋出異常
r.raise_for_status()
# r.encoding = r.apparent_encoding.
r.encoding = 'utf-8'
return r.text
except:
return '網(wǎng)絡(luò)連接異常'
# 分析貼吧的網(wǎng)頁(yè)文件,整理信息,保存在列表變量中
def get_content(url):
# 保存所有帖子信息
comments = []
# 獲取網(wǎng)址
html = get_html(url)
# 熬湯
soup = BeautifulSoup(html, 'lxml')
# 獲取li標(biāo)簽的列表
liTags = soup.find_all('li', attrs={'class': ' j_thread_list clearfix'})
# 遍歷帖子中需要的信息
for li in liTags:
# 保存文章信息到字典
comment = {}
# 當(dāng)爬蟲找不到信息時(shí)拋出異常
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('找不到相關(guān)文章信息')
return comments
# 將結(jié)果保存到本地
def Out2File(dict):
# 打開文件,使用追加模式
with open('D:\BDTB.txt', 'a+', encoding='utf-8') as f:
for comment in dict:
f.write('標(biāo)題: {} \t 鏈接:{} \t 發(fā)帖人:{} \t 發(fā)帖時(shí)間:{} \t 回復(fù)數(shù)量: {} \n'.format(
comment['title'], comment['link'], comment['name'], comment['time'], comment['replyNum']))
print('當(dāng)前頁(yè)面爬取完成')
def main(base_url, deep):
url_list = []
# 將需要爬取的url存入列表
for i in range(0, deep):
url_list.append(base_url + '&pn=' + str(50 * i))
print('所有網(wǎng)址下載完畢,開始篩選信息...')
# 遍歷分析所有數(shù)據(jù),并保存到本地
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'
# 設(shè)置需要爬取的頁(yè)碼數(shù)量
deep = 3
if __name__ == '__main__':
main(base_url, deep)
總結(jié)
以上是生活随笔為你收集整理的python爬取贴吧所有标题的评论_用BS4爬取贴吧文章的作者信息时,如何兼顾爬取高亮的作者信息?...的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: python3 正则表达式 嵌套表格_在
- 下一篇: 怎么连接屏幕_触控一体机怎么实现无线投屏