我们只需要复制User-Agent的值即可,代码如下:
# IE 9.0 的 User-Agent,包含在 user_agent里 ua_headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"} # url 连同 headers,一起构造Request请求,这个请求将附带 IE9.0 浏览器的User-Agent request = urllib.request.Request("http://www.baidu.com", headers = ua_headers) # 向服务器发送这个请求 response = urllib.request.urlopen(request) html = response.read() html加user-agent-请求信息
添加一个特定的header
import urllib2 url = "http://www.itcast.cn" #IE 9.0 的 User-Agent user_agent = {"User-Agent" : "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)"} request = urllib2.Request(url, headers = user_agent) #也可以通过调用Request.add_header() 添加/修改一个特定的header request.add_header("Connection", "keep-alive") # 也可以通过调用Request.get_header()来查看header信息 # request.get_header(header_name="Connection") response = urllib2.urlopen(request) print response.code #可以查看响应状态码 html = response.read() print html随机添加/修改User-Agent
import urllib2 import random url = "http://www.itcast.cn" ua_list = [ "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1", "Mozilla/5.0 (X11; CrOS i686 2268.111.0) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1092.0 Safari/536.6", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1090.0 Safari/536.6" ] user_agent = random.choice(ua_list) request = urllib2.Request(url) #也可以通过调用Request.add_header() 添加/修改一个特定的header request.add_header("User-Agent", user_agent) # get_header()的字符串参数,第一个字母大写,后面的全部小写 request.get_header("User-agent") response = urllib2.urlopen(request) html = response.read() print html 1.5. Response的其他用法 response.read() # 读取爬取的内容 response.getcode() # 返回HTTP的响应码, 200=OK response.geturl() # 返回数据的是具体哪个URL, 防止重定向 'http://www.baidu.com' response.info() # 返回服务器响应的抱头信息