日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

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

發布時間:2025/3/19 python 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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爬取贴吧文章的作者信息时,如何兼顾爬取高亮的作者信息?...的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。