from urllib import parse模塊的使用


一、介紹

定義了url的標准接口,實現url的各種抽取
parse模塊的作用:url的解析,合並,編碼,解碼

二、代碼

實現url的識別和分段

方法1.urlparse

url:待解析的url
scheme='':假如解析的url沒有協議,可以設置默認的協議,如果url有協議,設置此參數無效
allow_fragments=True:是否忽略錨點,默認為True表示不忽略,為False表示忽略

from urllib import parse
url = 'https://www.cnblogs.com/angelyan/'
result = parse.urlparse(url=url,scheme='http',allow_fragments=True)
print(result)
print(result.scheme)

(scheme='https', netloc='www.cnblogs.com', path='/angelyan/', params='', query='', fragment='')
scheme:表示協議
netloc:域名
path:路徑
params:參數
query:查詢條件,一般都是get請求的url
fragment:錨點,用於直接定位頁
面的下拉位置,跳轉到網頁的指定位置

方法2.urlunparse

可以實現url的構造

url_parmas = ('https', 'www.cnblogs.com', '/angelyan/', '', 'name=maple', 'log')
#components:是一個可迭代對象,長度必須為6
result = parse.urlunparse(url_parmas)
print(result)

返回結果:
https://www.cnblogs.com/angelyan/?name=maple#log

方法3.urljoin

傳遞一個基礎連接,根據基礎連接可以將某一個不完整的鏈接拼接為一個完整鏈接

base_url = 'https://www.cnblogs.com'
sub_url = '/angelyan/?name=maple#log'
full_url = parse.urljoin(base_url,sub_url)
print(full_url)

返回結果:
https://www.cnblogs.com/angelyan/?name=maple#log

方法4.urlencode

將字典形式的參數序列化為url編碼后的字符串,常用來構造get請求和post請求的參數


parmas = {
    'name':'maple',
    'age':18
}
parmas_str = parse.urlencode(parmas)
print(parmas_str)

返回結果:
name=maple&age=18

parmas_str = 'name=maple&age=18'
# 將url編碼格式的參數反序列化為字典類型
parmas = parse.parse_qs(parmas_str)
print(parmas)

返回結果:
{'name': ['maple'], 'age': ['18']}

方法5.quote編碼

可以將中文轉換為url編碼格式

tt = time.strftime("%a %b %d %Y %H:%M:%S", time.localtime())
send_time = tt +  ' GMT+0800 (中國標准時間)
print(parse.quote(send_time))
url = 'https://www.xinxindai.com/findPassword/sendSMS.html?'+ parse.quote(send_time)+'&mobileNo='+phone+'&imageCode='+code`
print(url)

返回結果:
Sun%20Feb%2007%202021%2016%3A55%3A14%20GMT%2B0800%20%28%E4%B8%AD%E5%9B%BD%E6%A0%87%E5%87%86%E6%97%B6%E9%97%B4%29
https://www.xinxindai.com/findPassword/sendSMS.html?Sun Feb 07 2021 16%3A55%3A14 GMT%2B0800 (中國標准時間)&mobileNo=13811352043&imageCode=9389

方法6.unquote解碼

from urllib import parse
url = 'https://www.xinxindai.com/findPassword/sendSMS.html?Sun%20Feb%2007%202021%2016%3A55%3A14%20GMT%2B0800%20%28%E4%B8%AD%E5%9B%BD%E6%A0%87%E5%87%86%E6%97%B6%E9%97%B4%29&mobileNo=13811352043&imageCode=9389
'
print(parse.unquote(url)

返回結果:
https://www.xinxindai.com/findPassword/sendSMS.html?Sun Feb 07 2021 15:42:10 GMT+0800 (中國標准時間)&mobileNo=13811352043&imageCode=9389


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM