python?包實(shí)現(xiàn)?urllib?網(wǎng)絡(luò)請求操作
更新時間:2022年04月19日 17:40:49 作者:autofelix
這篇文章主要介紹了python包實(shí)現(xiàn)urllib網(wǎng)絡(luò)請求操作,urllib?是?Python?標(biāo)準(zhǔn)庫中用于網(wǎng)絡(luò)請求的庫,下面urllib的相關(guān)資料介紹,需要的小伙伴可以參考一下
一、簡介
- 是一個 python 內(nèi)置包,不需要額外安裝即可使用
- urllib 是 Python 標(biāo)準(zhǔn)庫中用于網(wǎng)絡(luò)請求的庫,內(nèi)置四個模塊,分別是
- 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)行爬取
二、發(fā)起請求
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'))
三、攜帶參數(shù)請求
- 請求某些網(wǎng)頁時需要攜帶一些數(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'))
四、獲取響應(yīng)數(shù)據(jù)
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'))
五、設(shè)置headers
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'))
七、認(rèn)證登錄
- 有些網(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'))
八、設(shè)置cookie
- 如果請求的頁面每次需要身份驗(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)
十、HTTP異常
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)
十三、參數(shù)拼接
- 在訪問url時,我們常常需要傳遞很多的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)
十五、拼接鏈接
- 如果拼接的是兩個鏈接,則以返回后面的鏈接
- 如果拼接是一個鏈接和參數(shù),則返回拼接后的內(nèi)容
from urllib.parse import urljoin print(urljoin('http://www.baidu.com', 'index.html'))
十六、字典轉(zhuǎn)換參數(shù)
from urllib.parse import urlencode params = { 'name': 'autofelix', 'age': 27 } baseUrl = 'http://www.baidu.com?' print(baseUrl + urlencode(params))
到此這篇關(guān)于python 包中的 urllib 網(wǎng)絡(luò)請求教程的文章就介紹到這了,更多相關(guān) urllib 網(wǎng)絡(luò)請求 內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
三步實(shí)現(xiàn)Django Paginator分頁的方法
這篇文章主要介紹了三步實(shí)現(xiàn)Django Paginator分頁的方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-06-06Python3 文章標(biāo)題關(guān)鍵字提取的例子
今天小編就為大家分享一篇Python3 文章標(biāo)題關(guān)鍵字提取的例子,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-08-08python獲取文件版本信息、公司名和產(chǎn)品名的方法
這篇文章主要介紹了python獲取文件版本信息、公司名和產(chǎn)品名的方法,是Python程序設(shè)計中非常實(shí)用的技巧,需要的朋友可以參考下2014-10-10