urllib.request?模塊
urllib.request模塊定義了以下函數(shù):
urllib.request.urlopen(url,data=None,?[timeout,?]*,cafile=None,capath=None,cadefault=False,context=None)
參數(shù):
打開url鏈接,可以是字符串或者是Request對(duì)象脸侥。
data必須是一個(gè)定義了向服務(wù)器所發(fā)送額外數(shù)據(jù)的對(duì)象建邓,或者如果沒有必要數(shù)據(jù)的話,就是None值睁枕」俦撸可以查閱Request獲取詳細(xì)信息。
url.request模塊在HTTP請(qǐng)求中使用了HTTP/1.1外遇,并且包含了Connection:close頭部注簿。
可選的timeout參數(shù)指定阻止諸如連接嘗試等操作的超時(shí)時(shí)間(以秒為單位)(如果未指定,將使用全局默認(rèn)超時(shí)設(shè)置)跳仿。這實(shí)際上只適用于HTTP诡渴,HTTPS和FTP連接。
如果指定了context菲语,則它必須是描述各種SSL選項(xiàng)的ssl.SSLContext實(shí)例妄辩。 有關(guān)更多詳細(xì)信息,請(qǐng)參閱HTTPSConnection山上。
可選的cafile和capath參數(shù)為HTTPS請(qǐng)求指定一組可信的CA證書眼耀。cafile應(yīng)指向包含一系列CA證書的單個(gè)文件,而capath應(yīng)指向散列證書文件的目錄胶哲。 更多信息可以在ssl.SSLContext.load_verify_locations()中找到畔塔。
cadefault參數(shù)被忽略。
返回值:
該函數(shù)總是返回一個(gè)可以作為context manager使用的對(duì)象鸯屿,并且具有方法澈吨,例如;
geturl()-返回檢索的資源的URL,通常用于確定是否遵循重定向;
info()-以email.message_from_string()實(shí)例的形式返回頁面的元信息(如headers)(可快速參考HTTP Headers);
getcode()-返回響應(yīng)的HTTP狀態(tài)碼寄摆。
對(duì)于HTTP和HTTPS URL谅辣,此函數(shù)返回稍微修改的http.client.HTTPResponse對(duì)象。 除上述三種新方法之外婶恼,msg屬性還包含與reason屬性(服務(wù)器返回的原因短語)相同的信息桑阶,而不是HTTPResponse文檔中指定的響應(yīng)標(biāo)頭。
對(duì)于由傳統(tǒng)URLopener和FancyURLopener類明確處理的FTP勾邦,文件和數(shù)據(jù)URL和請(qǐng)求蚣录,此函數(shù)返回一個(gè)urllib.response.addinfourl對(duì)象。
在協(xié)議錯(cuò)誤上引發(fā)URLError眷篇。
請(qǐng)注意萎河,如果沒有處理請(qǐng)求的handler,則可能返回None(盡管默認(rèn)安裝的全局OpenerDirector使用UnknownHandler來確保永不發(fā)生這種情況)。
另外虐杯,如果檢測到代理設(shè)置(例如玛歌,如果設(shè)置了諸如http_proxy的* _proxy環(huán)境變量),則默認(rèn)安裝ProxyHandler擎椰,并確保通過代理處理請(qǐng)求支子。
import urllib.request
response=urllib.request.urlopen('https://www.python.org')
#請(qǐng)求站點(diǎn)獲得一個(gè)HTTPResponse對(duì)象
#print(response.read().decode('utf-8')) #返回網(wǎng)頁內(nèi)容
#print(response.getheader('server')) #返回響應(yīng)頭中的server值
#print(response.getheaders()) #以列表元祖對(duì)的形式返回響應(yīng)頭信息
#print(response.fileno()) #返回文件描述符
#print(response.version) #返回版本信息
#print(response.status) #返回狀態(tài)碼200,404代表網(wǎng)頁未找到
#print(response.debuglevel) #返回調(diào)試等級(jí)
#print(response.closed) #返回對(duì)象是否關(guān)閉布爾值
#print(response.geturl()) #返回檢索的URL
#print(response.info()) #返回網(wǎng)頁的頭信息
#print(response.getcode()) #返回響應(yīng)的HTTP狀態(tài)碼
#print(response.msg) #訪問成功則返回ok
#print(response.reason) #返回狀態(tài)信息
# 按行讀取
# print(response.readline())# 讀取一行
# print(response.readline()) # 讀取下一行
# print( response.readlines()) # 讀取多行达舒。得到一個(gè)列表 每個(gè)元素是一行
使用案例
1值朋、簡單讀取網(wǎng)頁信息
import urllib.request
response =urllib.request.urlopen('http://python.org/')
html =response.read()
2、使用request
urllib.request.Request(url, data=None, headers={}, method=None)
使用request()來包裝請(qǐng)求休弃,再通過urlopen()獲取頁面吞歼。
import urllib.request
req =urllib.request.Request('http://python.org/')
response =urllib.request.urlopen(req)
the_page =response.read()
3、發(fā)送數(shù)據(jù)塔猾,以登錄知乎為例
import gzip
import re
import urllib.request
import urllib.parse
import http.cookiejar
defung zip(data):
??try:
????print("嘗試解壓縮...")
????data =gzip.decompress(data)
????print("解壓完畢")
??except:
????print("未經(jīng)壓縮,無需解壓")
? returndata
def getXSRF(data):
??cer =re.compile('name=\"_xsrf\" value=\"(.*)\"',flags =0)
??strlist =cer.findall(data)
??return strlist[0]
def getOpener(head):
??# cookies 處理
??cj =http.cookiejar.CookieJar()
??pro =urllib.request.HTTPCookieProcessor(cj)
??opener =urllib.request.build_opener(pro)
??header =[]
??forkey,value inhead.items():
????elem =(key,value)
????header.append(elem)
??opener.addheaders =header
??returnopener
# header信息可以通過firebug獲得
header ={
??'Connection': 'Keep-Alive',
??'Accept': 'text/html, application/xhtml+xml, */*',
??'Accept-Language': 'en-US,en;q=0.8,zh-Hans-CN;q=0.5,zh-Hans;q=0.3',
??'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0',
??'Accept-Encoding': 'gzip, deflate',
??'Host': 'www.zhihu.com',
??'DNT': '1'
}
url ='http://www.zhihu.com/'
opener =getOpener(header)
op =opener.open(url)
data =op.read()
data =ungzip(data)
_xsrf =getXSRF(data.decode())
url +="login/email"
email ="登錄賬號(hào)"
password ="登錄密碼"
postDict ={
??'_xsrf': _xsrf,
??'email': email,
??'password': password,
??'rememberme': 'y'
}
postData =urllib.parse.urlencode(postDict).encode()
op =opener.open(url,postData)
data =op.read()
data =ungzip(data)
print(data.decode())
4稽坤、http錯(cuò)誤
import urllib.request
req =urllib.request.Request('http://www.lz881228.blog.163.com')
try:
??urllib.request.urlopen(req)
except urllib.error.HTTPError as e:
print(e.code)
print(e.read().decode("utf8"))
5丈甸、異常處理
from urllib.request importRequest, urlopen
from urllib.error importURLError, HTTPError
req =Request("http://www.abc.com/")
try:
??response =urlopen(req)
except HTTPError as e:
??print('The server couldn't fulfill the request.')
??print('Error code: ', e.code)
except URLError as e:
??print('We failed to reach a server.')
??print('Reason: ', e.reason)
else:
??print("good!")
??print(response.read().decode("utf8"))
6、http認(rèn)證
import urllib.request?
# create a password manager
password_mgr =urllib.request.HTTPPasswordMgrWithDefaultRealm()
# Add the username and password.
# If we knew the realm, we could use it instead of None.
top_level_url ="https://www.jb51.net/"
password_mgr.add_password(None, top_level_url, 'rekfan', 'xxxxxx')
handler =urllib.request.HTTPBasicAuthHandler(password_mgr)
# create "opener" (OpenerDirector instance)
opener =urllib.request.build_opener(handler)
# use the opener to fetch a URL
a_url ="https://www.jb51.net/"
x =opener.open(a_url)
print(x.read())
# Install the opener.
# Now all calls to urllib.request.urlopen use our opener.
urllib.request.install_opener(opener)
a =urllib.request.urlopen(a_url).read().decode('utf8')
print(a)
7尿褪、使用代理
import urllib.request
proxy_support =urllib.request.ProxyHandler({'sock5': 'localhost:1080'})
opener =urllib.request.build_opener(proxy_support)
urllib.request.install_opener(opener)
a =urllib.request.urlopen("http://www.baidu.com").read().decode("utf8")
print(a)
8睦擂、超時(shí)
import socket
import urllib.request
# timeout in seconds
timeout = 2
socket.setdefaulttimeout(timeout)
# this call to urllib.request.urlopen now uses the default timeout
# we have set in the socket module
req = urllib.request.Request('//www.jb51.net /')
a = urllib.request.urlopen(req).read()
print(a)
import?urllib.request
response = urllib.request.urlopen("https://httpbin.org/get",timeout=1)
print(response.read().decode("utf-8"))