一.UA检测与UA伪装
UA.User-Agent(请求载体的身份标识) UA检测:.门户网站的服务器会检测对应请求的载体身份标识.如果检测到请求的载体身份标识为某一款浏览器,说明该请求是一个正常的请求,但是如果检测到请求的载体体身份标识不是基于某一款浏览器的.则表示该请求不是正常的请求(爬虫),则会拒绝该请求 UA伪装:.让爬虫对应的请求载体身分标识伪装成某一款浏览器
写以下两行代码即可
headers={
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:97.0) Gecko/20100101 Firefox/97.0'
}
response = requests.get(url=url,params=param,headers=headers)
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import requests
if __name__ == '__main__':
headers={
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:97.0) Gecko/20100101 Firefox/97.0'
}
url='https://www.sogou.com/web?'
kw=raw_input('你想要爬取什么:')
param={
'query':kw
}
response = requests.get(url=url,params=param,headers=headers)
page_text = response.text
fileName = kw+'.html'
with open(fileName.decode('utf-8'),'w') as fp:
fp.write(page_text)
print (fileName,'保存成功!!!')
|