import urllib2
- urllib2.urlopen([ url ], data, timeout)
url:可以是一個字符串,也可以是一個Request對象
data:提交的參數(shù)
timeout:以秒為單位
A:字符串
response = urllib2.urlopen('http://www.baidu.com')
html = response.read()
B:Request對象
request = urllib2.Request('http://www.baidu.com')
response = urllib2.urlopen(request)
html = response.read()
- urllib2.Request([ url ], data, headers, origin_req_host, unverifiable)
data:
post提交的數(shù)據(jù),數(shù)據(jù)應該是緩存在一個標準的application/x-www-form-urlencode格式中,
urllib.urlencode()用映射或二元組返回一個這種格式的字符串
即post發(fā)送的數(shù)據(jù)需要被以標準的格式進行編碼
headers:
字典類型,也可使用add_header(key, value)方法添加
origin_req_host:
RFC2965定義的源交互的request-host
默認的取值是cookielib.request_host(self)
這是由用戶發(fā)起的原始請求的主機名或ip地址
例如:
如果請求的是一個HTML文檔中的圖像,這應該是包含該圖像的頁面請求的request-host
unverifiable:
代表請求是否是無法驗證的,由RFC2965定義,默認false
一個無法驗證的請求:
某用戶的URL沒有足夠的權限來被接受
例如:
如果請求的是在HTML文檔中的圖像,但是用戶沒有自動抓取圖像的權限,則該值為true
A:
url = 'http://www.test.com/'
values = {
'name' : 'Michael Foord',
'location' : 'Northampton',
'language' : 'Python'
}
data = urllib.urlencode(values)
req = urllib2.Request(url, data, headers)
response = urllib2.urlopen(req)
html = response.read()
B:
生成Request對象時,已經(jīng)初始化header,可利用add_header支架
req = urllib2.Request(url)
req.add_header('Referer', 'http://python.org/')
response = urllib2.urlopen(req)
C:
opener = urllib2.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
opener.open(url)
- urllib2.build_opener 和 urllib2.install_opener
創(chuàng)建opener
opener = urllib2.build_opener()
不調(diào)用urllib2.install_opener 使用open方法
opener.open(url)
調(diào)用urllib2.install_opener后,使用urllib2.urlopen方法
urllib2.install_opener(opener)
urllib2.urlopen(url)