Python urllib request模塊發(fā)送請求實現(xiàn)過程解析
1.Request()的參數(shù)
import urllib.request
request=urllib.request.Request('https://python.org')
response=urllib.request.urlopen(request)
print(response.read().decode('utf-8'))
通過構(gòu)造這個數(shù)據(jù)結(jié)構(gòu),一方面可以我們可以將請求獨立成一個對象,另一方面可以更加豐富和靈活地配置參數(shù)。
它的構(gòu)造方法如下:
class.urllib.request.Request(url,data=None,headers={},origin_rep_host=None,unverifiable=False,method=None)
參數(shù):
1.url必傳參數(shù)
2.data,必須傳bytes類型。如果是字典,先使用urllib.parse里的urlencode()
3.headers,是一個字典,請求頭,直接構(gòu)造或者用add_header()方法添加
4.origin_rep_host,請求方的名稱或者ip地址
5.unverifiable,默認(rèn)為false,表示這個請求是否無法驗證。如果沒有抓取的權(quán)限,此時值就是true。
6.method,用來指示請求使用的方法。
嘗試傳入多個參數(shù)構(gòu)建請求:
from urllib import request,parse url='http://httpbin.org/post' headers={ 'Url-Agent':'Mozilla/4.0(compatible;MSIE 5.5;Windows NT)', 'Host':'httpbin.org' }#也可以使用add_header()方法添加headers:#req=request.Request(url=url,data=data,method='POST')#req.add_header('User-Agent','Mozilla/4.0(compatible;MSIE 5.5;Windows NT)') dict={ 'name':'Germey' } data=bytes(parse.urlencode(dict),encoding='utf-8')#用urlencode()將dict轉(zhuǎn)換成bytes類型,傳遞給data req=request.Request(url=url,data=data,headers=headers,method='POST') response=request.urlopen(req) print(response.read().decode('utf-8'))
運(yùn)行結(jié)果:
2.Handler與Opener
Handler:
它是各種處理器,幾乎可以做到HTTP請求中的所有事情。
urllib.request模塊里的BaseHandler類,它是所有其他Headler的父類,它提供了最基本的方法。
Opener:
例如urlopen()就是一個Opener,它是urllib為我們提供的。
它們的關(guān)系是:使用Handler來構(gòu)建Opener。
3.用法
驗證:
創(chuàng)建一個需要驗證的網(wǎng)站,我這里使用的是IIS
遇到的問題:
IIS怎樣安裝與配置-百度經(jīng)驗 (baidu.com)
IIS網(wǎng)站如何設(shè)置基本身份驗證-百度經(jīng)驗 (baidu.com)
window10家庭版解決IIS中萬維網(wǎng)服務(wù)的安全性中無Windows身份驗證 - enjoryWeb - 博客園 (cnblogs.com)
代碼:
from urllib.request import HTTPPasswordMgrWithDefaultRealm,HTTPBasicAuthHandler,build_opener from urllib.error import URLError username='username'#填上自己的用戶名和密碼 password='password' url='http://localhost:5000/' p=HTTPPasswordMgrWithDefaultRealm() p.add_password(None,url,username,password)#添加用戶名和密碼,建立了一個處理驗證的Handler auth_handler=HTTPBasicAuthHandler(p)#基本認(rèn)證 opener=build_opener(auth_handler)#利用Handler構(gòu)建一個Opener try: result=opener.open(url)#打開鏈接 html=result.read().decode('utf-8') print(html)#結(jié)果打印html源碼內(nèi)容 except URLError as e: print(e.reason)
代理:
添加代理,在本地搭建一個代理,運(yùn)行在9743端口上。
代碼:
from urllib.request import ProxyHandler,build_opener from urllib.error import URLError proxy_handler=ProxyHandler({ 'http':'http://127.0.0.1:9743', 'https':'https://127.0.0.1:9743' })#構(gòu)建一個Handler opener=build_opener(proxy_handler)#構(gòu)建一個Opener try: response=opener.open('https://www.baidu.com') print(response.read().decode('utf-8')) except URLError as e: print(e.reason)
Cookies:
將網(wǎng)站的Cookies獲取下來:
代碼:
import http.cookiejar,urllib.request cookie=http.cookiejar.CookieJar()#聲明一個CookieJar對象 handler=urllib.request.HTTPCookieProcessor(cookie)#構(gòu)建一個Handler opener=urllib.request.build_opener(handler)#構(gòu)建一個Opener response=opener.open('http://www.baidu.com') for item in cookie: print(item.name+"="+item.value)
運(yùn)行結(jié)果:
將Cookie輸出成文件格式:
代碼:
import http.cookiejar,urllib.request
filename='cookies.txt'
cookie=http.cookiejar.MozillaCookieJar(filename)
#MozillaCookieJar()生成文件時用到,用來處理Cookie和文件相關(guān)的事件
#如果要保存LWP格式的Cookies文件,可以改為:
#cookie=http.cookiejar.LWPCookieJar(filename)handler=urllib.request.HTTPCookieProcessor(cookie)
opener=urllib.request.build_opener(handler)
response=opener.open('http://www.baidu.com')
cookie.save(ignore_discard=True,ignore_expires=True)
運(yùn)行結(jié)果:
# Netscape HTTP Cookie File # http://curl.haxx.se/rfc/cookie_spec.html # This is a generated file! Do not edit. .baidu.com TRUE / FALSE 1638359640 BAIDUID 9BB1BA4FDD840EBD956A3D2EFB6BF883:FG=1 .baidu.com TRUE / FALSE 3754307287 BIDUPSID 9BB1BA4FDD840EBD25D00EE8183D1125 .baidu.com TRUE / FALSE H_PS_PSSID 1445_33119_33059_31660_33099_33101_26350_33199 .baidu.com TRUE / FALSE 3754307287 PSTM 1606823639 www.baidu.com FALSE / FALSE BDSVRTM 7 www.baidu.com FALSE / FALSE BD_HOME 1
LWP格式:
#LWP-Cookies-2.0 Set-Cookie3: BAIDUID="DDF5CB401A1543ED614CE42962D48099:FG=1"; path="/"; domain=".baidu.com"; path_spec; domain_dot; expires="2021-12-01 12:04:18Z"; comment=bd; version=0 Set-Cookie3: BIDUPSID=DDF5CB401A1543ED00860C3997C3282C; path="/"; domain=".baidu.com"; path_spec; domain_dot; expires="2088-12-19 15:18:25Z"; version=0 Set-Cookie3: H_PS_PSSID=1430_33058_31254_33098_33101_33199; path="/"; domain=".baidu.com"; path_spec; domain_dot; discard; version=0 Set-Cookie3: PSTM=1606824257; path="/"; domain=".baidu.com"; path_spec; domain_dot; expires="2088-12-19 15:18:25Z"; version=0 Set-Cookie3: BDSVRTM=0; path="/"; domain="www.baidu.com"; path_spec; discard; version=0 Set-Cookie3: BD_HOME=1; path="/"; domain="www.baidu.com"; path_spec; discard; version=0
以LWP格式的文件為示例,展示讀取和利用的方法:
代碼:
import http.cookiejar,urllib.request
cookie=http.cookiejar.LWPCookieJar()
#如果文件保存為Mozilla型瀏覽器格式,可以改為:
#cookie=http.cookiejar.MozillaCookieJar()cookie.load('cookies.txt',ignore_discard=True,ignore_expires=True)
#調(diào)用load()方法來讀取本地的Cookies文件,獲取Cookies的內(nèi)容handler=urllib.request.HTTPCookieProcessor(cookie)
opener=urllib.request.build_opener(handler)
response=opener.open('http://www.baidu.com')
print(response.read().decode('utf-8'))
運(yùn)行結(jié)果:輸出網(wǎng)頁源代碼。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Pytorch 解決自定義子Module .cuda() tensor失敗的問題
這篇文章主要介紹了Pytorch 解決自定義子Module .cuda() tensor失敗的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06Python實現(xiàn)數(shù)據(jù)集劃分(訓(xùn)練集和測試集)
這篇文章主要為大家詳細(xì)介紹了Python是如何實現(xiàn)數(shù)據(jù)集劃分的,分為訓(xùn)練集和測試集,文中的實現(xiàn)方法講解詳細(xì),感興趣的小伙伴可以了解一下2023-05-05Opencv圖像添加椒鹽噪聲、高斯濾波去除噪聲原理以及手寫Python代碼實現(xiàn)方法
椒鹽噪聲的特征非常明顯,為圖像上有黑色和白色的點,下面這篇文章主要給大家介紹了關(guān)于Opencv圖像添加椒鹽噪聲、高斯濾波去除噪聲原理以及手寫Python代碼實現(xiàn)的相關(guān)資料,文中通過實例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-09-09Python實現(xiàn)針對json中某個關(guān)鍵字段進(jìn)行排序操作示例
這篇文章主要介紹了Python實現(xiàn)針對json中某個關(guān)鍵字段進(jìn)行排序操作,涉及Python json數(shù)組排序及l(fā)ambda表達(dá)式相關(guān)操作技巧,需要的朋友可以參考下2018-12-12