爬虫百度的时候,出现的问题

本文介绍使用Tornado的HTTPClient抓取百度页面时遇到的防爬虫问题及解决方法。通过在HTTP请求头部添加User-Agent字段,成功绕过了百度的网页跳转防御,实现了正常的数据抓取。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

from  tornado.httpclient import HTTPClient

client = HTTPClient()
response = client.fetch('https://www.baidu.com/')
print(response.body)
client.close()

'''
b'<html>\r\n<head>\r\n\t<script>\r\n\t\tlocation.replace(location.href.replace("https://","http://"));\r\n\t</script>\r\n</head>\r\n<body>\r\n\t<noscript><meta http-equiv="refresh" content="0;url=http://www.baidu.com/"></noscript>\r\n</body>\r\n</html>'
'''

用tornado的HTTPClient抓取百度页面的时候,返回的是“网页跳转”??应该是百度的防爬虫手段吧。

解决的方法是,伪装成浏览器。

from  tornado.httpclient import HTTPClient

client = HTTPClient()
response = client.fetch('https://www.baidu.com/',headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/17.17134'})
print(response.body)
client.close()

就是在http头里添加User-Agent字段说明(覆盖掉原本的User-Agent)

GET / HTTP/1.1
Host: www.baidu.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/17.17134

这个User-Agent是我从edge上拿的,可是,明明只是edge啊,为什么也要伪装成其他浏览器??

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值