代碼如下,
import requests
import sys
import time
word_url = 'http://index.baidu.com/api/SearchApi/thumbnail?area=0&word={}'
COOKIES = ''
def decrypt(t, e):
n = list(t)
i = list(e)
a = {}
result = []
ln = int(len(n) / 2)
start = n[ln:]
end = n[:ln]
for j, k in zip(start, end):
a.update({k: j})
for j in e:
result.append(a.get(j))
return ''.join(result)
def get_index_home(keyword):
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.90 Safari/537.36',
'Cookie': COOKIES
}
resp = requests.get(word_url.format(keyword), headers=headers)
j = resp.json()
uniqid = j.get('data').get('uniqid')
return get_ptbk(uniqid)
def get_ptbk(uniqid):
url = 'http://index.baidu.com/Interface/ptbk?uniqid={}'
ptbk_headers = {
'Accept': 'application/json, text/plain, */*',
'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'zh-CN,zh;q=0.9',
'Cache-Control': 'no-cache',
'Cookie': COOKIES,
'DNT': '1',
'Host': 'index.baidu.com',
'Pragma': 'no-cache',
'Proxy-Connection': 'keep-alive',
'Referer': 'http://index.baidu.com/v2/main/index.html',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.90 Safari/537.36',
'X-Requested-With': 'XMLHttpRequest',
}
resp = requests.get(url.format(uniqid), headers=ptbk_headers)
if resp.status_code != 200:
print('獲取uniqid失敗')
sys.exit(1)
return resp.json().get('data')
def get_index_data(keyword, start='2011-01-03', end='2019-08-05'):
url = f'http://index.baidu.com/api/SearchApi/index?word={keyword}&area=0&startDate={start}&endDate={end}'
headers = {
'Accept': 'application/json, text/plain, */*',
'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'zh-CN,zh;q=0.9',
'Cache-Control': 'no-cache',
'Cookie': COOKIES,
'DNT': '1',
'Host': 'index.baidu.com',
'Pragma': 'no-cache',
'Proxy-Connection': 'keep-alive',
'Referer': 'http://index.baidu.com/v2/main/index.html',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.90 Safari/537.36',
'X-Requested-With': 'XMLHttpRequest',
}
resp = requests.get(url, headers=headers)
if resp.status_code != 200:
print('獲取指數失敗')
sys.exit(1)
data = resp.json().get('data').get('userIndexes')[0]
uniqid = data.get('uniqid')
ptbk = get_index_home(uniqid)
while ptbk is None or ptbk == '':
ptbk = get_index_home(uniqid)
all_data = data.get('all').get('data')
result = decrypt(ptbk, all_data)
result = result.split(',')
print(result)
if __name__ == '__main__':
get_index_data('酷安')
有錯的行:

報錯如下:

請求大神幫忙解決,這是爬百度搜索指數的代碼。
uj5u.com熱心網友回復:
f-strings這個語法是python3.6以上才有的,你的python版本低了一點點https://zhuanlan.zhihu.com/p/62774871
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/60805.html
上一篇:【求助】python小白的dataframe的索引問題
下一篇:提取目錄下c檔案包含關鍵字的行
