def bd_searout(key,t1,t2):
'''key是搜索的关键词,t1是起始时间,t2是结束时间,
t1,t2需要输入datetime类型的时间数据,例如:先定义t1=datetime(2020,1,1),
然后再输入到函数中。函数返回在百度搜索的指定时间段的关键词的搜索结果的数量'''
import requests,re
from datetime import datetime
t1_stamp = datetime.timestamp(t1)
t2_stamp = datetime.timestamp(t2)
header={'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9'\
,'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36'}
url = f'https://www.baidu.com/s?wd={key}&ie=UTF-8&gpc=stf={t1_stamp},{t2_stamp}|stftype=2&tfflag=1'
result = requests.get(url,headers = header)
text_out = result.text
p = re.compile('百度为您找到相关结果约.+个')
out = p.search(text_out).group()
return out
示例:
t1 = datetime(2020,1,1)
t2 = datetime(2020,3,31)
out = bd_searout('波波',t1,t2)
print(out)
结果:
百度为您找到相关结果约18,600,000个