res = requests.get('https://image.baidu.com/search/index?tn=baiduimage&ps=1&ct=201326592&lm=-1&cl=2&nc=1&ie=utf-8&word=%E5%B0%8F%E7%8B%97')
我想用这行代码获取百度图片搜索“小狗”的结果,但是获取不到正确的源代码HTML,这是为什么?
res = requests.get('https://image.baidu.com/search/index?tn=baiduimage&ps=1&ct=201326592&lm=-1&cl=2&nc=1&ie=utf-8&word=%E5%B0%8F%E7%8B%97')
我想用这行代码获取百度图片搜索“小狗”的结果,但是获取不到正确的源代码HTML,这是为什么?
需要添加headers。
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36', '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','Accept-Encoding': 'gzip, deflate, br'
}
res = requests.get(
'https://image.baidu.com/search/index?tn=baiduimage&ps=1&ct=201326592&lm=-1&cl=2&nc=1&ie=utf-8&word=%E5%B0%8F%E7%8B%97',headers=headers)
res.encoding='utf-8'
print(res.text)
如有帮助,请点击我这个回答右上方的【采纳】按钮。