例如百度查询“天气”
import urllib.request,re
keywd = '天气'
keywd = urllib.request.quote(keywd) #中文时需转换
url = 'http://www.baidu.com/s?wd='+keywd
data = urllib.request.urlopen(url).read().decode("utf-8")
pat = "title:'(.*?)',"
rst = re.compile(pat).findall(data)
print(rst)
结果:
解决办法:添加对应的浏览器版本信息;(注意,不要用最新版本的;我在测试时使用最新浏览器的版本号,也是返回空)
import urllib.request,re
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/82.0.4051.0 Safari/537.36 Edg/82.0.425.0'}
keywd = '天气'
keywd = urllib.request.quote(keywd) #中文时需转换
url = 'http://www.baidu.com/s?wd='+keywd
data = urllib.request.urlopen(url).read().decode("utf-8")
pat = "title:'(.*?)',"
rst = re.compile(pat).findall(data)
print(rst)
结果返回就正常了