国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

Python urllib request模塊發(fā)送請(qǐng)求實(shí)現(xiàn)過(guò)程解析

瀏覽:8日期:2022-07-02 16:08:07

1.Request()的參數(shù)

import urllib.request

request=urllib.request.Request(’https://python.org’)response=urllib.request.urlopen(request)print(response.read().decode(’utf-8’))

通過(guò)構(gòu)造這個(gè)數(shù)據(jù)結(jié)構(gòu),一方面可以我們可以將請(qǐng)求獨(dú)立成一個(gè)對(duì)象,另一方面可以更加豐富和靈活地配置參數(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è)字典,請(qǐng)求頭,直接構(gòu)造或者用add_header()方法添加

4.origin_rep_host,請(qǐng)求方的名稱或者ip地址

5.unverifiable,默認(rèn)為false,表示這個(gè)請(qǐng)求是否無(wú)法驗(yàn)證。如果沒(méi)有抓取的權(quán)限,此時(shí)值就是true。

6.method,用來(lái)指示請(qǐng)求使用的方法。

嘗試傳入多個(gè)參數(shù)構(gòu)建請(qǐng)求:

from urllib import request,parseurl=’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類型,傳遞給datareq=request.Request(url=url,data=data,headers=headers,method=’POST’)response=request.urlopen(req)print(response.read().decode(’utf-8’))

運(yùn)行結(jié)果:

Python urllib request模塊發(fā)送請(qǐng)求實(shí)現(xiàn)過(guò)程解析

2.Handler與Opener

Handler:

它是各種處理器,幾乎可以做到HTTP請(qǐng)求中的所有事情。

urllib.request模塊里的BaseHandler類,它是所有其他Headler的父類,它提供了最基本的方法。

Opener:

例如urlopen()就是一個(gè)Opener,它是urllib為我們提供的。

它們的關(guān)系是:使用Handler來(lái)構(gòu)建Opener。

3.用法

驗(yàn)證:

創(chuàng)建一個(gè)需要驗(yàn)證的網(wǎng)站,我這里使用的是IIS

Python urllib request模塊發(fā)送請(qǐng)求實(shí)現(xiàn)過(guò)程解析

遇到的問(wèn)題:

IIS怎樣安裝與配置-百度經(jīng)驗(yàn) (baidu.com)

IIS網(wǎng)站如何設(shè)置基本身份驗(yàn)證-百度經(jīng)驗(yàn) (baidu.com)

window10家庭版解決IIS中萬(wàn)維網(wǎng)服務(wù)的安全性中無(wú)Windows身份驗(yàn)證 - enjoryWeb - 博客園 (cnblogs.com)

代碼:

from urllib.request import HTTPPasswordMgrWithDefaultRealm,HTTPBasicAuthHandler,build_openerfrom urllib.error import URLErrorusername=’username’#填上自己的用戶名和密碼password=’password’url=’http://localhost:5000/’p=HTTPPasswordMgrWithDefaultRealm()p.add_password(None,url,username,password)#添加用戶名和密碼,建立了一個(gè)處理驗(yàn)證的Handlerauth_handler=HTTPBasicAuthHandler(p)#基本認(rèn)證opener=build_opener(auth_handler)#利用Handler構(gòu)建一個(gè)Openertry: result=opener.open(url)#打開(kāi)鏈接 html=result.read().decode(’utf-8’) print(html)#結(jié)果打印html源碼內(nèi)容except URLError as e: print(e.reason)

代理:

添加代理,在本地搭建一個(gè)代理,運(yùn)行在9743端口上。

代碼:

from urllib.request import ProxyHandler,build_openerfrom urllib.error import URLErrorproxy_handler=ProxyHandler({ ’http’:’http://127.0.0.1:9743’, ’https’:’https://127.0.0.1:9743’})#構(gòu)建一個(gè)Handleropener=build_opener(proxy_handler)#構(gòu)建一個(gè)Openertry: response=opener.open(’https://www.baidu.com’) print(response.read().decode(’utf-8’))except URLError as e: print(e.reason)

Cookies:

將網(wǎng)站的Cookies獲取下來(lái):

代碼:

import http.cookiejar,urllib.requestcookie=http.cookiejar.CookieJar()#聲明一個(gè)CookieJar對(duì)象handler=urllib.request.HTTPCookieProcessor(cookie)#構(gòu)建一個(gè)Handleropener=urllib.request.build_opener(handler)#構(gòu)建一個(gè)Openerresponse=opener.open(’http://www.baidu.com’)for item in cookie: print(item.name+'='+item.value)

運(yùn)行結(jié)果:

Python urllib request模塊發(fā)送請(qǐng)求實(shí)現(xiàn)過(guò)程解析

將Cookie輸出成文件格式:

代碼:

import http.cookiejar,urllib.request

filename=’cookies.txt’

cookie=http.cookiejar.MozillaCookieJar(filename)#MozillaCookieJar()生成文件時(shí)用到,用來(lái)處理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 1606823639www.baidu.com FALSE / FALSE BDSVRTM 7www.baidu.com FALSE / FALSE BD_HOME 1

LWP格式:

#LWP-Cookies-2.0Set-Cookie3: BAIDUID='DDF5CB401A1543ED614CE42962D48099:FG=1'; path='/'; domain='.baidu.com'; path_spec; domain_dot; expires='2021-12-01 12:04:18Z'; comment=bd; version=0Set-Cookie3: BIDUPSID=DDF5CB401A1543ED00860C3997C3282C; path='/'; domain='.baidu.com'; path_spec; domain_dot; expires='2088-12-19 15:18:25Z'; version=0Set-Cookie3: H_PS_PSSID=1430_33058_31254_33098_33101_33199; path='/'; domain='.baidu.com'; path_spec; domain_dot; discard; version=0Set-Cookie3: PSTM=1606824257; path='/'; domain='.baidu.com'; path_spec; domain_dot; expires='2088-12-19 15:18:25Z'; version=0Set-Cookie3: BDSVRTM=0; path='/'; domain='www.baidu.com'; path_spec; discard; version=0Set-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()方法來(lái)讀取本地的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)頁(yè)源代碼。

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。

標(biāo)簽: Python 編程
相關(guān)文章:
主站蜘蛛池模板: 德兴市| 永丰县| 金沙县| 湖北省| 湘乡市| 周至县| 唐河县| 平陆县| 昂仁县| 景东| 墨玉县| 都昌县| 蒙阴县| 武乡县| 永春县| 八宿县| 上林县| 米泉市| 化州市| 九江市| 孝感市| 文山县| 宜城市| 长岭县| 白河县| 抚远县| 吉首市| 南昌市| 江源县| 房产| 呼图壁县| 保康县| 任丘市| 镇平县| 蓬安县| 中阳县| 连南| 安图县| 新乡市| 彰化市| 三都|