正文
python 怎么模拟加header(如User-Agent、Content-Type等等)
小程序:扫一扫查出行
【扫一扫了解最新限行尾号】
复制小程序
【扫一扫了解最新限行尾号】
复制小程序
# -*- coding: cp936 -*-
#python 27
#xiaodeng
#python 怎么模拟加header(如User-Agent、Content-Type等等) #办法一:
import urllib,urllib2,time
opener=urllib2.build_opener()
opener.addheaders=[('User-agent','Mozilla/5.0')]#添加浏览器标识
data=opener.open('http://www.cnblogs.com/dengyg200891/')
print data.read()
time.sleep(5) #办法二
#加入header,首先需要一个Request对象
import urllib2
request=urllib2.Request('http://www.cnblogs.com/dengyg200891/')
request.add_header('User-Agent','fake-client')
response=urllib2.urlopen(request)
print response.read() #方式三
import urllib2,urllib
url='http://www.163.com'
headers={
'Accept':'text/html, */*;q=0.01',
'User-Agent':'gzip'
}
data=None
req=urllib2.Request(url,data,headers)
response=urllib2.urlopen(req)
print response.read()