欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python urllib庫的使用詳解

 更新時間:2021年04月13日 15:33:08   作者:牛新龍的IT技術(shù)博客  
這篇文章主要介紹了python urllib庫的使用詳解,幫助大家更好的利用python學(xué)習(xí)爬蟲,感興趣的朋友可以了解下

相關(guān):urllib是python內(nèi)置的http請求庫,本文介紹urllib三個模塊:請求模塊urllib.request、異常處理模塊urllib.error、url解析模塊urllib.parse。

1、請求模塊:urllib.request

python2

import urllib2
response = urllib2.urlopen('http://httpbin.org/robots.txt')

python3

import urllib.request
res = urllib.request.urlopen('http://httpbin.org/robots.txt')
urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)
urlopen()方法中的url參數(shù)可以是字符串,也可以是一個Request對象

#url可以是字符串
import urllib.request

resp = urllib.request.urlopen('http://www.baidu.com')
print(resp.read().decode('utf-8'))  # read()獲取響應(yīng)體的內(nèi)容,內(nèi)容是bytes字節(jié)流,需要轉(zhuǎn)換成字符串
##url可以也是Request對象
import urllib.request

request = urllib.request.Request('http://httpbin.org')
response = urllib.request.urlopen(request)
print(response.read().decode('utf-8'))

data參數(shù):post請求

# coding:utf8
import urllib.request, urllib.parse

data = bytes(urllib.parse.urlencode({'word': 'hello'}), encoding='utf8')
resp = urllib.request.urlopen('http://httpbin.org/post', data=data)
print(resp.read())

urlopen()中的參數(shù)timeout:設(shè)置請求超時時間:

# coding:utf8
#設(shè)置請求超時時間
import urllib.request

resp = urllib.request.urlopen('http://httpbin.org/get', timeout=0.1)
print(resp.read().decode('utf-8'))

響應(yīng)類型:

# coding:utf8
#響應(yīng)類型
import urllib.request

resp = urllib.request.urlopen('http://httpbin.org/get')
print(type(resp))

響應(yīng)的狀態(tài)碼、響應(yīng)頭:

# coding:utf8
#響應(yīng)的狀態(tài)碼、響應(yīng)頭
import urllib.request

resp = urllib.request.urlopen('http://www.baidu.com')
print(resp.status)
print(resp.getheaders())  # 數(shù)組(元組列表)
print(resp.getheader('Server'))  # "Server"大小寫不區(qū)分

200
[('Bdpagetype', '1'), ('Bdqid', '0xa6d873bb003836ce'), ('Cache-Control', 'private'), ('Content-Type', 'text/html'), ('Cxy_all', 'baidu+b8704ff7c06fb8466a83df26d7f0ad23'), ('Date', 'Sun, 21 Apr 2019 15:18:24 GMT'), ('Expires', 'Sun, 21 Apr 2019 15:18:03 GMT'), ('P3p', 'CP=" OTI DSP COR IVA OUR IND COM "'), ('Server', 'BWS/1.1'), ('Set-Cookie', 'BAIDUID=8C61C3A67C1281B5952199E456EEC61E:FG=1; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com'), ('Set-Cookie', 'BIDUPSID=8C61C3A67C1281B5952199E456EEC61E; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com'), ('Set-Cookie', 'PSTM=1555859904; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com'), ('Set-Cookie', 'delPer=0; path=/; domain=.baidu.com'), ('Set-Cookie', 'BDSVRTM=0; path=/'), ('Set-Cookie', 'BD_HOME=0; path=/'), ('Set-Cookie', 'H_PS_PSSID=1452_28777_21078_28775_28722_28557_28838_28584_28604; path=/; domain=.baidu.com'), ('Vary', 'Accept-Encoding'), ('X-Ua-Compatible', 'IE=Edge,chrome=1'), ('Connection', 'close'), ('Transfer-Encoding', 'chunked')]
BWS/1.1

使用代理:urllib.request.ProxyHandler():

# coding:utf8
proxy_handler = urllib.request.ProxyHandler({'http': 'http://www.example.com:3128/'})
proxy_auth_handler = urllib.request.ProxyBasicAuthHandler()
proxy_auth_handler.add_password('realm', 'host', 'username', 'password')

opener = urllib.request.build_opener(proxy_handler, proxy_auth_handler)
# This time, rather than install the OpenerDirector, we use it directly:
resp = opener.open('http://www.example.com/login.html')
print(resp.read())

2、異常處理模塊:urllib.error

異常處理實例1:

# coding:utf8
from urllib import error, request

try:
    resp = request.urlopen('http://www.blueflags.cn')
except error.URLError as e:
    print(e.reason)

異常處理實例2:

# coding:utf8
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')

異常處理實例3:

# coding:utf8
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')

3、url解析模塊:urllib.parse

parse.urlencode

# coding:utf8
from urllib import request, parse

url = 'http://httpbin.org/post'
headers = {
    'Host': 'httpbin.org',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36'
}
dict = {'name': 'Germey'}
data = bytes(parse.urlencode(dict), encoding='utf8')
req = request.Request(url=url, data=data, headers=headers, method='POST')
resp = request.urlopen(req)
print(resp.read().decode('utf-8'))
{
"args": {},
"data": "",
"files": {},
"form": {
"name": "Thanlon"
},
"headers": {
"Accept-Encoding": "identity",
"Content-Length": "12",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "httpbin.org",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36"
},
"json": null,
"origin": "117.136.78.194, 117.136.78.194",
"url": "https://httpbin.org/post"
}

add_header方法添加請求頭:

# coding:utf8
from urllib import request, parse

url = 'http://httpbin.org/post'
dict = {'name': 'Thanlon'}
data = bytes(parse.urlencode(dict), encoding='utf8')
req = request.Request(url=url, data=data, method='POST')
req.add_header('User-Agent',
               'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36')
resp = request.urlopen(req)
print(resp.read().decode('utf-8'))

parse.urlparse:

# coding:utf8
from urllib.parse import urlparse

result = urlparse('http://www.baidu.com/index.html;user?id=1#comment')
print(type(result))
print(result)

<class 'urllib.parse.ParseResult'>
ParseResult(scheme='http', netloc='www.baidu.com', path='/index.html', params='user', query='id=1', fragment='comment')

from urllib.parse import urlparse

result = urlparse('www.baidu.com/index.html;user?id=1#comment', scheme='https')
print(type(result))
print(result)

<class 'urllib.parse.ParseResult'>
ParseResult(scheme='https', netloc='', path='www.baidu.com/index.html', params='user', query='id=1', fragment='comment')

# coding:utf8
from urllib.parse import urlparse

result = urlparse('http://www.baidu.com/index.html;user?id=1#comment', scheme='https')
print(result)

ParseResult(scheme='http', netloc='www.baidu.com', path='/index.html', params='user', query='id=1', fragment='comment')

# coding:utf8
from urllib.parse import urlparse

result = urlparse('http://www.baidu.com/index.html;user?id=1#comment',allow_fragments=False)
print(result)

ParseResult(scheme='http', netloc='www.baidu.com', path='/index.html', params='user', query='id=1', fragment='comment')

parse.urlunparse:

# coding:utf8
from urllib.parse import urlunparse

data = ['http', 'www.baidu.com', 'index.html', 'user', 'name=Thanlon', 'comment']
print(urlunparse(data))

parse.urljoin:

# coding:utf8
from urllib.parse import urljoin

print(urljoin('http://www.bai.com', 'index.html'))
print(urljoin('http://www.baicu.com', 'https://www.thanlon.cn/index.html'))#以后面為基準

urlencode將字典對象轉(zhuǎn)換成get請求的參數(shù):

# coding:utf8
from urllib.parse import urlencode

params = {
    'name': 'Thanlon',
    'age': 22
}
baseUrl = 'http://www.thanlon.cn?'
url = baseUrl + urlencode(params)
print(url)

4、Cookie

cookie的獲取(保持登錄會話信息):

# coding:utf8
#cookie的獲取(保持登錄會話信息)
import urllib.request, http.cookiejar

cookie = http.cookiejar.CookieJar()
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
res = opener.open('http://www.baidu.com')
for item in cookie:
    print(item.name + '=' + item.value)

MozillaCookieJar(filename)形式保存cookie

# coding:utf8
#將cookie保存為cookie.txt
import http.cookiejar, urllib.request

filename = 'cookie.txt'
cookie = http.cookiejar.MozillaCookieJar(filename)
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
res = opener.open('http://www.baidu.com')
cookie.save(ignore_discard=True, ignore_expires=True)

LWPCookieJar(filename)形式保存cookie:

# coding:utf8
import http.cookiejar, urllib.request

filename = 'cookie.txt'
cookie = http.cookiejar.LWPCookieJar(filename)
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
res = opener.open('http://www.baidu.com')
cookie.save(ignore_discard=True, ignore_expires=True)

讀取cookie請求,獲取登陸后的信息

# coding:utf8
import http.cookiejar, urllib.request

cookie = http.cookiejar.LWPCookieJar()
cookie.load('cookie.txt', ignore_discard=True, ignore_expires=True)
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
resp = opener.open('http://www.baidu.com')
print(resp.read().decode('utf-8'))

以上就是python urllib庫的使用詳解的詳細內(nèi)容,更多關(guān)于python urllib庫的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • python輸出決策樹圖形的例子

    python輸出決策樹圖形的例子

    今天小編就為大家分享一篇python輸出決策樹圖形的例子,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-08-08
  • python實現(xiàn)漢諾塔方法匯總

    python實現(xiàn)漢諾塔方法匯總

    本文給大家匯總了幾種使用Python結(jié)合遞歸算法實現(xiàn)漢諾塔的方法,非常的簡單實用,對大家學(xué)習(xí)Python很有幫助,希望大家能夠喜歡
    2016-07-07
  • 在Python程序中進行文件讀取和寫入操作的教程

    在Python程序中進行文件讀取和寫入操作的教程

    這篇文章主要介紹了在Python程序中進行文件讀取和寫入操作的教程,是Python學(xué)習(xí)當(dāng)中的基礎(chǔ)知識,需要的朋友可以參考下
    2015-04-04
  • 在PyTorch中實現(xiàn)高效的多進程并行處理

    在PyTorch中實現(xiàn)高效的多進程并行處理

    PyTorch是一個流行的深度學(xué)習(xí)框架,一般情況下使用單個GPU進行計算時是十分方便的,但是當(dāng)涉及到處理大規(guī)模數(shù)據(jù)和并行處理時,需要利用多個GPU,所以這篇文章我們將介紹如何利用torch.multiprocessing模塊,在PyTorch中實現(xiàn)高效的多進程處理,需要的朋友可以參考下
    2024-07-07
  • Python中斷多重循環(huán)的思路總結(jié)

    Python中斷多重循環(huán)的思路總結(jié)

    在本文里小編給大家整理的是關(guān)于Python中斷多重循環(huán)的思路以及相關(guān)知識點,有需要的朋友們可以學(xué)習(xí)下。
    2019-10-10
  • Python編程實現(xiàn)從字典中提取子集的方法分析

    Python編程實現(xiàn)從字典中提取子集的方法分析

    這篇文章主要介紹了Python編程實現(xiàn)從字典中提取子集的方法,結(jié)合實例形式對比分析了Python采用字典推導(dǎo)式與序列轉(zhuǎn)換實現(xiàn)字典提取子集的相關(guān)操作技巧與優(yōu)缺點,需要的朋友可以參考下
    2018-02-02
  • Python?OpenCV實現(xiàn)任意角度二維碼矯正

    Python?OpenCV實現(xiàn)任意角度二維碼矯正

    這篇文章主要為大家詳細介紹了如何利用Python?OpenCV實現(xiàn)任意角度的二維碼快速矯正,文中的示例代碼講解詳細,感興趣的小伙伴可以嘗試一下
    2022-05-05
  • Python tkinter實現(xiàn)日期選擇器

    Python tkinter實現(xiàn)日期選擇器

    這篇文章主要為大家詳細介紹了Python tkinter實現(xiàn)日期選擇器,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-02-02
  • python3實現(xiàn)在二叉樹中找出和為某一值的所有路徑(推薦)

    python3實現(xiàn)在二叉樹中找出和為某一值的所有路徑(推薦)

    這篇文章主要介紹了python3實現(xiàn)在二叉樹中找出和為某一值的所有路徑,本文通過一個實例demo給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下
    2019-12-12
  • python gui開發(fā)——制作抖音無水印視頻下載工具(附源碼)

    python gui開發(fā)——制作抖音無水印視頻下載工具(附源碼)

    這篇文章主要介紹了python gui開發(fā)——制作抖音無水印視頻下載工具(附源碼)的相關(guān)資料,幫助大家更好的理解和學(xué)習(xí)使用python,感興趣的朋友可以了解下
    2021-02-02

最新評論