Python中關於URL的處理(基於Python2.7版本)
阿新 • • 發佈:2019-02-04
參考官方文件:https://docs.python.org/3/library/urllib.html點選開啟連結
1、 完整的url語法格式:
協議://使用者名稱@密碼:子域名.域名.頂級域名:埠號/目錄/檔名.檔案字尾?引數=值#標識
2 、urlparse模組對url的處理方法
urlparse模組對url的主要處理方法有:urljoin/urlsplit/urlunsplit/urlparse等。該模組對url的定義採用六元組的形式:schema://netloc/path;parameters?query#fragment。其中,netloc包含下表的後4個屬性
urlparse()
利用urlparse()方法對url進行解析,返回六元組;urlunparse()對六元組進行組合- urljoin()
利用urljoin()方法對絕對url地址與相對url地址進行拼合
主要使用urljoin()比較常用——給出以下示例:
>>>from urllib.parse import urljoin >>> urljoin("http://www.chachabei.com/folder/currentpage.html", "anotherpage.html") 'http://www.chachabei.com/folder/anotherpage.html' >>> urljoin("http://www.chachabei.com/folder/currentpage.html", "/anotherpage.html") 'http://www.chachabei.com/anotherpage.html' >>> urljoin("http://www.chachabei.com/folder/currentpage.html", "folder2/anotherpage.html") 'http://www.chachabei.com/folder/folder2/anotherpage.html' >>> urljoin("http://www.chachabei.com/folder/currentpage.html", "/folder2/anotherpage.html") 'http://www.chachabei.com/folder2/anotherpage.html' >>> urljoin("http://www.chachabei.com/abc/folder/currentpage.html", "/folder2/anotherpage.html") 'http://www.chachabei.com/folder2/anotherpage.html' >>> urljoin("http://www.chachabei.com/abc/folder/currentpage.html", "../anotherpage.html") 'http://www.chachabei.com/abc/anotherpage.html'
- urlsplit()
利用urlsplit()方法可以對URL進行分解;與urlparse()相比,urlsplit()函式返回一個五元組,沒有parameter引數。
相應的,urlunsplit()方法可以對urlsplit()分解的五元組進行合併。兩種方法組合在一起,可以對URL進行有效地格式化,特殊字元在此過程中得到轉換。
3 urllib模組對url的編碼與解碼
urllib模組的quote_plus()方法實現對url的編碼,包括對中文的編碼;unquote_plus()方法實現對url的解碼,包括對中文的解碼。