爬虫获取微博首页热搜
生活随笔
收集整理的這篇文章主要介紹了
爬虫获取微博首页热搜
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
爬蟲獲取微博首頁熱搜
步驟:
- 打開微博首頁 https://s.weibo.com/top/summary?
- 右鍵點擊檢查,分析靜態網頁
- 將爬取到的內容保存為csv文件格式
需要導入的庫
import requests from lxml import etree import pandas as pd話不多說,直接上源碼!
import requests from lxml import etree import pandas as pd url = 'https://s.weibo.com/top/summary?' headers = {'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Mobile Safari/537.36 Edg/91.0.864.70' }def get_url(url):try:response = requests.get(url, headers=headers)if response.status_code == 200:return response.textexcept requests.ConnectionError as e:print(e.args)def get_hot():hotlist = [] #熱搜內容列表,用來保存內容hot_url_list=[] #熱搜url列表index_list=[] #索引號列表items = get_url(url) #調用函數,獲取網頁response.texthtml = etree.HTML(items)# 初始化hot_list = html.xpath('/html/body/div/section/ul/li')#xpath定位,可在瀏覽器直接復制j=1#遍歷所有li列表for i in hot_list:#獲取熱搜內容hot = i.xpath('./a/span/text()')[0] #一直搞不懂[0]是什么意思hotlist.append(hot)#獲取內容的urlhot_url = i.xpath('./a/@href')[0]hot_url="https://s.weibo.com/"+str(hot_url)#需要組合正確的url,才能打開hot_url_list.append(hot_url)print(j,hot,hot_url)index_list.append(j)j=j+1#保存文件file=pd.DataFrame(data={'編號':index_list,'內容':hotlist,'url':hot_url_list})file.to_csv('微博熱搜.csv',encoding='utf_8_sig')#調用函數,完成爬取! get_hot()運行結果:
文件
到此,便完成了今天微博熱搜的獲取。
關于以上代碼,要留意的就是組合url,源碼是沒有"https://s.weibo.com/"這一前綴的,估計是對我的考驗,哈哈!
還有就是hot = i.xpath(’./a/span/text()’)[0] 后面的[0]不加會報錯,但我又不知道是什么意思,還望大神指點迷津。
xpath只是略懂皮毛,知識有限,還望走過路過多多指教!
總結
以上是生活随笔為你收集整理的爬虫获取微博首页热搜的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2019蓝桥杯本科B组C-C++决赛题
- 下一篇: 腾讯王卡运营坑之一:web容器优雅停机缓