温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

python爬虫之User Agent

发布时间:2020-07-28 11:46:51 来源:网络 阅读:2162 作者:Forande 栏目:系统运维

在学习爬虫的过程中在有的时候没使用头在使用python的爬虫脚本刚爬了两次,就只是测试了一下就打不开这个网页了,刚开始还一直迷糊着,到后来才知道,python在做爬虫的时候默认的user agent就是python的大版本,python2.7.的User-Agent: Python-urllib/2.7;python3.5.的User-Agent: Python-urllib/3.5

下面来做个试验:
python代码如下:

python2

import urllib2

url = "http://www.baidu.com/"

request = urllib2.Request(url)

response = urllib2.urlopen(request)

print(response.read())

python3

from urllib import request

url = "http://www.baidu.com/"

req = request.Request(url)

response = request.urlopen(req)

print(response.read().decode()

我们开启fiddler,运行完成代码,然后在fiddler上面查看下我们的数据
python爬虫之User Agent
很明显就是python的版本,
因此我们在学习爬虫的时候无论爬什么,代码最好都要加上这个头信息

下面我们在代码上加入一个头

from urllib import request

headers = {
    "User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64"
}

url = "http://www.baidu.com/"

req = request.Request(url,headers=headers)

response = request.urlopen(req)

print(response.read().decode())

抓包的结果如下:
python爬虫之User Agent

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI