1. 程式人生 > 其它 >bs實戰-新浪微博

bs實戰-新浪微博

今天我們想要提取一下新網微博熱搜的題目和熱度

利用之前我們所學的知識,今天這個問題應該不難解決

我直接展示一下程式碼,程式碼裡的註釋大家可以看一下:

import requests
from bs4 import BeautifulSoup

#定義url和請求頭
url = 'https://s.weibo.com/top/summary?Refer=top_hot&topnav=1&wvr=6'
headers = {
        "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.106 Safari/537.36
"} #傳送請求 response = requests.get(url,headers=headers) content = response.content.decode('utf8') #例項化BeautifulSoup物件 soup = BeautifulSoup(content,'lxml') #提取資料 sinas=[] tds = soup.find_all('td',class_="td-02")[1:] for td in tds: #熱搜的內容 event = td.find_all('a')[0].string # print(event) # break
#熱度 hot = td.find_all('span')[0].string # print(event,hot) # break sina = { 'event':event, 'hot':hot } sinas.append(sina) print(sinas)

最後打印出來的結果: