Python百度指數獲取腳本下載并保存
前言
有時候大家需要知道一個關鍵詞在互聯網上的熱度,想知道某個關鍵詞的熱度變化趨勢。大家可能就是使用百度指數、微信指數之類的。非常好用,但是就是不能把數據下載保存下來,不方便我們后面進行操作。
我無意間看到別人提供的python腳本,可以對百度指數進行爬蟲,于是我稍微修改了部分代碼,做了一個可以直接返回pd.DataFrame的數據框的類;然后后面又加了一個小的可視化代碼。這里和大家分享,只要使用這個腳本,就可以將百度指數數據下載下來,并且保存。
具體步驟
1. 獲得cookie值
百度指數是需要登陸,進行用戶驗證,因此,我們要登陸百度指數,然后隨便搜索一個關鍵詞,比如python。然后在網頁空白地方,右鍵打開【檢查】,然后進入【網絡】
這個時候會發(fā)現【網絡】里面都是空的,需要重新刷新網頁即可看到所有內容。內容太多了,注意選擇【Fetch/XHR】.
然后找到index?
開頭的文件,查看他的【標頭】、查看他的【Cookie】.將這個cookie的值復制
2. 使用我的代碼
基礎代碼,只要復制好就行:
import?requests import?json from?datetime?import?date,?timedelta import?pandas?as?pd class?DownloadBaiDuIndex(object): ????def?__init__(self,?cookie): ????????self.cookie?=?cookie ????????self.headers?=?{ ????????????"Connection":?"keep-alive", ????????????"Accept":?"application/json,?text/plain,?*/*", ????????????"User-Agent":?"Mozilla/5.0?(Windows?NT?10.0;?WOW64)?AppleWebKit/537.36?(KHTML,?like?Gecko)?Chrome/86.0.4240.198?Safari/537.36", ????????????"Sec-Fetch-Site":?"same-origin", ????????????"Sec-Fetch-Mode":?"cors", ????????????"Sec-Fetch-Dest":?"empty", ????????????"Referer":?"https://index.baidu.com/v2/main/index.html", ????????????"Accept-Language":?"zh-CN,zh;q=0.9", ????????????'Cookie':?self.cookie, ????????} ????def?decrypt(self,?ptbk,?index_data): ????????n?=?len(ptbk)?//?2 ????????a?=?dict(zip(ptbk[:n],?ptbk[n:])) ????????return?"".join([a[s]?for?s?in?index_data]) ????def?get_index_data_json(self,?keys,?start=None,?end=None): ????????words?=?[[{"name":?key,?"wordType":?1}]?for?key?in?keys] ????????words?=?str(words).replace("?",?"").replace("'",?""") ????????url?=?f'http://index.baidu.com/api/SearchApi/index?area=0&word={words}&area=0&startDate={start}&endDate={end}' ????????print(words,?start,?end) ????????res?=?requests.get(url,?headers=self.headers) ????????data?=?res.json()['data'] ????????uniqid?=?data['uniqid'] ????????url?=?f'http://index.baidu.com/Interface/ptbk?uniqid={uniqid}' ????????res?=?requests.get(url,?headers=self.headers) ????????ptbk?=?res.json()['data'] ????????result?=?{} ????????result["startDate"]?=?start ????????result["endDate"]?=?end ????????for?userIndexe?in?data['userIndexes']: ????????????name?=?userIndexe['word'][0]['name'] ????????????tmp?=?{} ????????????index_all?=?userIndexe['all']['data'] ????????????index_all_data?=?[int(e)?for?e?in?self.decrypt(ptbk,?index_all).split(",")] ????????????tmp["all"]?=?index_all_data ????????????index_pc?=?userIndexe['pc']['data'] ????????????index_pc_data?=?[int(e)?for?e?in?self.decrypt(ptbk,?index_pc).split(",")] ????????????tmp["pc"]?=?index_pc_data ????????????index_wise?=?userIndexe['wise']['data'] ????????????index_wise_data?=?[int(e) ???????????????????????????????for?e?in?self.decrypt(ptbk,?index_wise).split(",")] ????????????tmp["wise"]?=?index_wise_data ????????????result[name]?=?tmp ????????return?result ????def?GetIndex(self,?keys,?start=None,?end=None): ????????today?=?date.today() ????????if?start?is?None: ????????????start?=?str(today?-?timedelta(days=8)) ????????if?end?is?None: ????????????end?=?str(today?-?timedelta(days=2)) ????????try: ????????????raw_data?=?self.get_index_data_json(keys=keys,?start=start,?end=end) ????????????raw_data?=?pd.DataFrame(raw_data[keys[0]]) ????????????raw_data.index?=?pd.date_range(start=start,?end=end) ????????except?Exception?as?e: ????????????print(e) ????????????raw_data?=?pd.DataFrame({'all':?[],?'pc':?[],?'wise':?[]}) ????????finally: ????????????return?raw_data
使用上面的類:
使用上面的類,然后使用下面的代碼。先初始化類,然后在使用這個對象的GetIndex函數,里面的參數keys就是傳遞一個關鍵詞就行,要用列表形式傳遞。
說更加簡單一點的,只要把python替換成別的關鍵詞就行了,然后時間也都是文本形式,樣式就是'yyyy-mm-dd'形式就行。
cookie?=?'你的cookie值,注意使用英文單引號;就是直接復制就行了' #?初始化一個類 downloadbaiduindex?=?DownloadBaiDuIndex(cookie=cookie) data?=?downloadbaiduindex.GetIndex(keys=['python'],?start='2021-01-01',?end='2021-11-12') data
保存數據
如果想保存數據,直接可以這么寫:
data.to_csv('data.csv')
可視化
獲得數據已經很簡單了,接下來可視化,就是非常簡單的事情了,你用別的語言處理數據也都可以了。我這里簡單的畫一個時間序列圖:
import?plotly.graph_objects?as?go import?pandas?as?pd df?=?data fig?=?go.Figure([go.Scatter(x=df.index,?y=df['all'],?fill='tozeroy')]) fig.update_layout(template='plotly_white',?title='python?百度指數') fig.show() fig.write_html('python.html')
結果如下:
總結
上面基本上沒有任何難點了,只要沒把cookie復制錯,只要沒有把上面的參數寫錯就行。
到此這篇關于Python百度指數獲取腳本下載并保存的文章就介紹到這了,更多相關Python獲取腳本內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Python使用pymssql連接SQL?SEVER數據庫全流程
SQL Server是微軟推出的重量級的數據庫,目前有多個版本,如2000、2008、2012等,下面這篇文章主要給大家介紹了關于Python使用pymssql連接SQL?SEVER數據庫的相關資料,需要的朋友可以參考下2023-12-12