利用Python對百度今日熱點事件排行榜關鍵詞的爬取

百度今日熱點事件排行榜URL今日熱點事件排行榜


代碼:

#CrawBaiduTop.py
import requests
from bs4 import BeautifulSoup
import bs4

tops = []                                                                   #創建空列表,用於儲存詞條
url = 'http://top.baidu.com/buzz?b=341&c=513&fr=topbuzz_b1_c513'
r = requests.get(url, timeout=40)                                           #獲得url信息,設置40秒超時時間
r.raise_for_status()                                                        #失敗請求(非200響應)拋出異常
r.encoding = r.apparent_encoding                                            #根據內容分析出的編碼方式,備選編碼;
html = r.text                                                               #獲得的HTML文本                                 
table = BeautifulSoup(html,"html.parser").find("table")                     #對獲得的文本進行html解析,查找<table>內的信息
for words in table.find_all("a"):                                           #查找<table>內<a>的所有信息
    if words.string !='search' and words.string !='新聞' and words.string !='視頻'and words.string !='圖片':
        tops.append(words.string)                                           #append() 方法用於在列表末尾添加新對象
    else:
        continue
print(tops)

結果:


p.s. 新手入門,還望各位指教,歡迎提出任何優化代碼的意見

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章