您好,登錄后才能下訂單哦!
這篇文章主要講解了“python包中的urllib網(wǎng)絡(luò)請求怎么實(shí)現(xiàn)”,文中的講解內(nèi)容簡單清晰,易于學(xué)習(xí)與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學(xué)習(xí)“python包中的urllib網(wǎng)絡(luò)請求怎么實(shí)現(xiàn)”吧!
是一個(gè) python 內(nèi)置包,不需要額外安裝即可使用
urllib 是 Python 標(biāo)準(zhǔn)庫中用于網(wǎng)絡(luò)請求的庫,內(nèi)置四個(gè)模塊,分別是
urllib.request:用來打開和讀取 url,可以用它來模擬發(fā)送請求,獲取網(wǎng)頁響應(yīng)內(nèi)容
urllib.error:用來處理 urllib.request 引起的異常,保證程序的正常執(zhí)行
urllib.parse:用來解析 url,可以對 url 進(jìn)行拆分、合并等
urllib.robotparse:用來解析 robots.txt 文件,判斷網(wǎng)站是否能夠進(jìn)行爬取
import urllib.request # 方法一 resp = urllib.request.urlopen('http://www.baidu.com', timeout=1) print(resp.read().decode('utf-8')) # 方法二 request = urllib.request.Request('http://www.baidu.com') response = urllib.request.urlopen(request) print(response.read().decode('utf-8'))
請求某些網(wǎng)頁時(shí)需要攜帶一些數(shù)據(jù)
import urllib.parse import urllib.request params = { 'name':'autofelix', 'age':'25' } data = bytes(urllib.parse.urlencode(params), encoding='utf8') response = urllib.request.urlopen("http://www.baidu.com/", data=data) print(response.read().decode('utf-8'))
import urllib.request resp = urllib.request.urlopen('http://www.baidu.com') print(type(resp)) print(resp.status) print(resp.geturl()) print(resp.getcode()) print(resp.info()) print(resp.getheaders()) print(resp.getheader('Server'))
import urllib.request headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36' } request = urllib.request.Request(url="http://tieba.baidu.com/", headers=headers) response = urllib.request.urlopen(request) print(response.read().decode('utf-8'))
import urllib.request proxys = urllib.request.ProxyHandler({ 'http': 'proxy.cn:8080', 'https': 'proxy.cn:8080' }) opener = urllib.request.build_opener(proxys) urllib.request.install_opener(opener) request = urllib.request.Request(url="http://www.baidu.com/") response = urllib.request.urlopen(request) print(response.read().decode('utf-8'))
有些網(wǎng)站需要攜帶賬號和密碼進(jìn)行登錄之后才能繼續(xù)瀏覽網(wǎng)頁
import urllib.request url = "http://www.baidu.com/" user = 'autofelix' password = '123456' pwdmgr = urllib.request.HTTPPasswordMgrWithDefaultRealm() pwdmgr.add_password(None,url,user,password) auth_handler = urllib.request.HTTPBasicAuthHandler(pwdmgr) opener = urllib.request.build_opener(auth_handler) response = opener.open(url) print(response.read().decode('utf-8'))
如果請求的頁面每次需要身份驗(yàn)證,我們可以使用 Cookies
來自動登錄,免去重復(fù)登錄驗(yàn)證的操作
import http.cookiejar import urllib.request cookie = http.cookiejar.CookieJar() handler = urllib.request.HTTPCookieProcessor(cookie) opener = urllib.request.build_opener(handler) response = opener.open("http://www.baidu.com/") f = open('cookie.txt', 'a') for item in cookie: f.write(item.name+" = "+item.value+'\n') f.close()
from urllib import error, request try: resp = request.urlopen('http://www.baidu.com') except error.URLError as e: print(e.reason)
from urllib import error, request try: resp = request.urlopen('http://www.baidu.com') except error.HTTPError as e: print(e.reason, e.code, e.headers, sep='\n') except error.URLError as e: print(e.reason) else: print('request successfully')
import socket, urllib.request, urllib.error try: resp = urllib.request.urlopen('http://www.baidu.com', timeout=0.01) except urllib.error.URLError as e: print(type(e.reason)) if isinstance(e.reason,socket.timeout): print('time out')
from urllib import parse name = parse.quote('飛兔小哥') # 轉(zhuǎn)換回來 parse.unquote(name)
在訪問url時(shí),我們常常需要傳遞很多的url參數(shù)
而如果用字符串的方法去拼接url的話,會比較麻煩
from urllib import parse params = {'name': '飛兔', 'age': '27', 'height': '178'} parse.urlencode(params)
from urllib.parse import urlparse result = urlparse('http://www.baidu.com/index.html?user=autofelix') print(type(result)) print(result)
如果拼接的是兩個(gè)鏈接,則以返回后面的鏈接
如果拼接是一個(gè)鏈接和參數(shù),則返回拼接后的內(nèi)容
from urllib.parse import urljoin print(urljoin('http://www.baidu.com', 'index.html'))
from urllib.parse import urlencode params = { 'name': 'autofelix', 'age': 27 } baseUrl = 'http://www.baidu.com?' print(baseUrl + urlencode(params))
感謝各位的閱讀,以上就是“python包中的urllib網(wǎng)絡(luò)請求怎么實(shí)現(xiàn)”的內(nèi)容了,經(jīng)過本文的學(xué)習(xí)后,相信大家對python包中的urllib網(wǎng)絡(luò)請求怎么實(shí)現(xiàn)這一問題有了更深刻的體會,具體使用情況還需要大家實(shí)踐驗(yàn)證。這里是億速云,小編將為大家推送更多相關(guān)知識點(diǎn)的文章,歡迎關(guān)注!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。