Python百度指數(shù)獲取腳本下載并保存
前言
有時候大家需要知道一個關(guān)鍵詞在互聯(lián)網(wǎng)上的熱度,想知道某個關(guān)鍵詞的熱度變化趨勢。大家可能就是使用百度指數(shù)、微信指數(shù)之類的。非常好用,但是就是不能把數(shù)據(jù)下載保存下來,不方便我們后面進(jìn)行操作。
我無意間看到別人提供的python腳本,可以對百度指數(shù)進(jìn)行爬蟲,于是我稍微修改了部分代碼,做了一個可以直接返回pd.DataFrame的數(shù)據(jù)框的類;然后后面又加了一個小的可視化代碼。這里和大家分享,只要使用這個腳本,就可以將百度指數(shù)數(shù)據(jù)下載下來,并且保存。
具體步驟
1. 獲得cookie值
百度指數(shù)是需要登陸,進(jìn)行用戶驗證,因此,我們要登陸百度指數(shù),然后隨便搜索一個關(guān)鍵詞,比如python。然后在網(wǎng)頁空白地方,右鍵打開【檢查】,然后進(jìn)入【網(wǎng)絡(luò)】
這個時候會發(fā)現(xiàn)【網(wǎng)絡(luò)】里面都是空的,需要重新刷新網(wǎng)頁即可看到所有內(nèi)容。內(nèi)容太多了,注意選擇【Fetch/XHR】.
然后找到index?
開頭的文件,查看他的【標(biāo)頭】、查看他的【Cookie】.將這個cookie的值復(fù)制
2. 使用我的代碼
基礎(chǔ)代碼,只要復(fù)制好就行:
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函數(shù),里面的參數(shù)keys就是傳遞一個關(guān)鍵詞就行,要用列表形式傳遞。
說更加簡單一點的,只要把python替換成別的關(guān)鍵詞就行了,然后時間也都是文本形式,樣式就是'yyyy-mm-dd'形式就行。
cookie?=?'你的cookie值,注意使用英文單引號;就是直接復(fù)制就行了' #?初始化一個類 downloadbaiduindex?=?DownloadBaiDuIndex(cookie=cookie) data?=?downloadbaiduindex.GetIndex(keys=['python'],?start='2021-01-01',?end='2021-11-12') data
保存數(shù)據(jù)
如果想保存數(shù)據(jù),直接可以這么寫:
data.to_csv('data.csv')
可視化
獲得數(shù)據(jù)已經(jīng)很簡單了,接下來可視化,就是非常簡單的事情了,你用別的語言處理數(shù)據(jù)也都可以了。我這里簡單的畫一個時間序列圖:
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?百度指數(shù)') fig.show() fig.write_html('python.html')
結(jié)果如下:
總結(jié)
上面基本上沒有任何難點了,只要沒把cookie復(fù)制錯,只要沒有把上面的參數(shù)寫錯就行。
到此這篇關(guān)于Python百度指數(shù)獲取腳本下載并保存的文章就介紹到這了,更多相關(guān)Python獲取腳本內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python opencv實現(xiàn)旋轉(zhuǎn)矩形框裁減功能
這篇文章主要為大家詳細(xì)介紹了python opencv實現(xiàn)旋轉(zhuǎn)矩形框裁減功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-07-07python操作mongodb根據(jù)_id查詢數(shù)據(jù)的實現(xiàn)方法
這篇文章主要介紹了python操作mongodb根據(jù)_id查詢數(shù)據(jù)的實現(xiàn)方法,實例分析了Python根據(jù)pymongo不同版本操作ObjectId的技巧,需要的朋友可以參考下2015-05-05python-jwt用戶認(rèn)證食用教學(xué)的實現(xiàn)方法
這篇文章主要介紹了python-jwt用戶認(rèn)證食用教學(xué)的實現(xiàn)方法,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-01-01Python使用pymssql連接SQL?SEVER數(shù)據(jù)庫全流程
SQL Server是微軟推出的重量級的數(shù)據(jù)庫,目前有多個版本,如2000、2008、2012等,下面這篇文章主要給大家介紹了關(guān)于Python使用pymssql連接SQL?SEVER數(shù)據(jù)庫的相關(guān)資料,需要的朋友可以參考下2023-12-12