urllib.request 模塊-urlopen方法

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山上。

可選的cafilecapath參數(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"))

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市杖玲,隨后出現(xiàn)的幾起案子顿仇,更是在濱河造成了極大的恐慌,老刑警劉巖摆马,帶你破解...
    沈念sama閱讀 217,542評(píng)論 6 504
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件臼闻,死亡現(xiàn)場離奇詭異,居然都是意外死亡囤采,警方通過查閱死者的電腦和手機(jī)述呐,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,822評(píng)論 3 394
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來蕉毯,“玉大人乓搬,你說我怎么就攤上這事〈海” “怎么了进肯?”我有些...
    開封第一講書人閱讀 163,912評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長棉磨。 經(jīng)常有香客問我江掩,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,449評(píng)論 1 293
  • 正文 為了忘掉前任频敛,我火速辦了婚禮项郊,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘斟赚。我一直安慰自己着降,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,500評(píng)論 6 392
  • 文/花漫 我一把揭開白布拗军。 她就那樣靜靜地躺著任洞,像睡著了一般。 火紅的嫁衣襯著肌膚如雪发侵。 梳的紋絲不亂的頭發(fā)上交掏,一...
    開封第一講書人閱讀 51,370評(píng)論 1 302
  • 那天,我揣著相機(jī)與錄音刃鳄,去河邊找鬼盅弛。 笑死,一個(gè)胖子當(dāng)著我的面吹牛叔锐,可吹牛的內(nèi)容都是我干的挪鹏。 我是一名探鬼主播,決...
    沈念sama閱讀 40,193評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼愉烙,長吁一口氣:“原來是場噩夢(mèng)啊……” “哼讨盒!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起步责,我...
    開封第一講書人閱讀 39,074評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤返顺,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后蔓肯,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體遂鹊,經(jīng)...
    沈念sama閱讀 45,505評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,722評(píng)論 3 335
  • 正文 我和宋清朗相戀三年省核,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了稿辙。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,841評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡气忠,死狀恐怖邻储,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情旧噪,我是刑警寧澤吨娜,帶...
    沈念sama閱讀 35,569評(píng)論 5 345
  • 正文 年R本政府宣布,位于F島的核電站淘钟,受9級(jí)特大地震影響宦赠,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,168評(píng)論 3 328
  • 文/蒙蒙 一勾扭、第九天 我趴在偏房一處隱蔽的房頂上張望毡琉。 院中可真熱鬧,春花似錦妙色、人聲如沸桅滋。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,783評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽丐谋。三九已至,卻和暖如春煌珊,著一層夾襖步出監(jiān)牢的瞬間号俐,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,918評(píng)論 1 269
  • 我被黑心中介騙來泰國打工定庵, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留吏饿,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,962評(píng)論 2 370
  • 正文 我出身青樓洗贰,卻偏偏與公主長得像找岖,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子敛滋,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,781評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容

  • 什么是Urllib Urllib是python內(nèi)置的HTTP請(qǐng)求庫 包括以下模塊 urllib.request 請(qǐng)...
    msnchen閱讀 266評(píng)論 0 0
  • 什么是Urllib: Urllib是python內(nèi)置的HTTP請(qǐng)求庫 包括以下模塊 urllib.request ...
    啊煙雨閱讀 1,298評(píng)論 0 5
  • 管方文檔地址: 翻譯的是Python 3.5.2版本,對(duì)應(yīng)的urllib https://docs.python....
    kohlgrx閱讀 588評(píng)論 0 0
  • Urllib庫是python內(nèi)置的庫 什么是Urllib 1.urllib.request 請(qǐng)求模塊2.ur...
    謝謝_d802閱讀 702評(píng)論 0 3
  • 爬蟲的基本流程 一兴革、發(fā)送HTTP請(qǐng)求(Request)通過Python庫向目標(biāo)站點(diǎn)發(fā)送HTTP請(qǐng)求绎晃,等待服務(wù)器響應(yīng)...
    曉楓_0544閱讀 774評(píng)論 0 0