# 3.1.3 解析鏈接
## 1.說明
Urllib 庫里還提供了 parse 這個模塊,定義了處理 URL 的標準接口,例如實現 URL 各部分的抽取,合并以及鏈接轉換。支持如下協議的 URL 處理:file、ftp、gopher、hdl、http、https、imap、mailto、 mms、news、nntp、prospero、rsync、rtsp、rtspu、sftp、shttp、 sip、sips、snews、svn、svn+ssh、telnet、wais
## 2.urlparse\(\) {#1-urlparse}
urlparse\(\) 方法可以實現 URL 的識別和分段
實例:
```text
from urllib.parse import urlparse
result = urlparse("https://www.google.com.hk/search;user?q=python#content")
print(type(result),result,sep='\n')
```
運行結果:
```text
<class 'urllib.parse.ParseResult'>
ParseResult(scheme='https', netloc='www.google.com.hk', path='/search', params='user', query='q=python', fragment='content')
```
返回結果是一個 ParseResult 類型的對象,它包含了六個部分,分別是 scheme、netloc、path、params、query、fragment
實例url:
```text
https://www.google.com.hk/search;user?q=python#content
```
urlparse\(\) 方法將其拆分成了六部分,解析時有特定的分隔符,比如 :// 前面的就是 scheme,代表協議,第一個 / 前面便是 netloc,即域名,分號 ; 前面是 params,代表參數。
所以可以得出一個標準的鏈接格式如下:
```text
scheme://netloc/path;parameters?query#fragment
```
urlparse\(\)API 用法:
```text
urllib.parse.urlparse(urlstring, scheme='', allow_fragments=True)
```
* urlstring,是必填項,即待解析的 URL。
* scheme,是默認的協議(比如http、https等),假如這個鏈接沒有帶協議信息,會將這個作為默認的協議。
實例:
```text
result = urlparse("www.google.com.hk/search;user?q=python#content",scheme="https")
print(result)
```
運行結果:
```text
ParseResult(scheme='https', netloc='', path='www.google.com.hk/search', params='user', query='q=python', fragment='content')
```
scheme 參數只有在 URL 中不包含 scheme 信息時才會生效,如果 URL 中有 scheme 信息,那就返回解析出的 scheme
實例:
```text
result = urlparse("http://www.google.com.hk/search;user?q=python#content",scheme="https")
print(result)
```
運行結果:
```text
ParseResult(scheme='http', netloc='www.google.com.hk', path='/search', params='user', query='q=python', fragment='content')
```
* allow\_fragments,即是否忽略 fragment,如果它被設置為 False,fragment 部分就會被忽略,它會被解析為 path、parameters 或者 query 的一部分,fragment 部分為空。
實例:
```text
result = urlparse("http://www.google.com.hk/search;user?q=python#content",allow_fragments=False)
print(result)
```
運行結果:
```text
ParseResult(scheme='http', netloc='www.google.com.hk', path='/search', params='user', query='q=python#content', fragment='')
```
當 URL 中不包含 params 和 query 時, fragment 便會被解析為 path 的一部分
實例:
```text
result = urlparse("https://www.google.com.hk/webhp#content",allow_fragments=False)
print(result)
```
運行結果:
```text
ParseResult(scheme='https', netloc='www.google.com.hk', path='/webhp#content', params='', query='', fragment='')
```
返回結果 ParseResult 實際上是一個元組,我們可以用索引順序來獲取,也可以用屬性名稱獲取
實例:
```text
from urllib.parse import urlparse
result = urlparse('http://www.baidu.com/index.html#comment', allow_fragments=False)
print(result.scheme, result[0], result.netloc, result[1], sep='\n')
```
運行結果:
```text
http
http
www.baidu.com
www.baidu.com
```
## 3. urlunparse\(\) {#2-urlunparse}
* 與urlparse\(\)相反
* 接受的參數是一個可迭代對象,但是它的長度必須是 6,否則會拋出參數數量不足或者過多的問題
實例:
```text
from urllib.parse import urlunparse
data = ['http', 'www.google.com', 'index.html', 'name', 'q=6', 'comment']
print(urlunparse(data))
```
運行結果:
```text
http://www.google.com/index.html;name?q=6#comment
```
## 4. urlsplit\(\) {#3-urlsplit}
與urlparse\(\) 方法非常相似,只不過它不會單獨解析 parameters 這一部分,只返回五個結果
實例:
```text
from urllib.parse import urlsplit
result = urlsplit("https://www.google.com.hk/webhp#content")
print(result)
```
運行結果:
```text
SplitResult(scheme='https', netloc='www.google.com.hk', path='/webhp', query='', fragment='content')
```
返回結果是 SplitResult,其實也是一個元組類型,可以用屬性獲取值也可以用索引來獲取
實例:
```text
from urllib.parse import urlsplit
result = urlsplit("https://www.google.com.hk/webhp#content")
print(result.scheme,result[0])
```
運行結果:
```text
https https
```
## 5. urlunsplit\(\) {#4-urlunsplit}
* 與urlsplit\(\)相反
* 與 urlunparse\(\) 類似,也是將鏈接的各個部分組合成完整鏈接的方法,傳入的也是一個可迭代對象
實例:
```text
from urllib.parse import urlunsplit
data = ['http', 'www.google.com', 'index.html', 'q=6', 'comment']
print(urlunsplit(data))
```
運行結果:
```text
http://www.google.com/index.html?q=6#comment
```
## 6. urljoin\(\) {#5-urljoin}
生成鏈接還有另一個方法,利用 urljoin\(\) 方法我們可以提供一個 base\_url(基礎鏈接),新的鏈接作為第二個參數,方法會分析 base\_url 的 scheme、netloc、path, 如果這三項在新的鏈接里面不存在,那么就予以補充,如果新的鏈接存在,那么就使用新的鏈接的部分。base\_url 中的 parameters、query、fragments 是不起作用的。
實例:
```text
from urllib.parse import urljoin
print(urljoin('http://www.baidu.com', 'FAQ.html'))
# 會覆蓋前面的url
print(urljoin('http://www.baidu.com', 'https://cuiqingcai.com/FAQ.html'))
print(urljoin('http://www.baidu.com/about.html', 'https://cuiqingcai.com/FAQ.html'))
print(urljoin('http://www.baidu.com/about.html', 'https://cuiqingcai.com/FAQ.html?question=2'))
print(urljoin('http://www.baidu.com?wd=abc', 'https://cuiqingcai.com/index.php'))
print(urljoin('http://www.baidu.com', '?category=2#comment'))
print(urljoin('www.baidu.com', '?category=2#comment'))
print(urljoin('www.baidu.com#comment', '?category=2'))
```
運行結果:
```text
http://www.baidu.com/FAQ.html
https://cuiqingcai.com/FAQ.html
https://cuiqingcai.com/FAQ.html
https://cuiqingcai.com/FAQ.html?question=2
https://cuiqingcai.com/index.php
http://www.baidu.com?category=2#comment
www.baidu.com?category=2#comment
www.baidu.com?category=2
```
## 7. urlencode\(\) {#6-urlencode}
構造get請求參數
實例:
```text
from urllib.parse import urlencode
# 構造參數字典
params = {
'wd':'python',
}
base_url = 'https://www.baidu.com/s?'
url = base_url + urlencode(params)
print(url)
```
運行結果:
```text
https://www.baidu.com/s?wd=python
```
## 8. parse\_qs\(\) {#7-parseqs}
parse\_qs\(\) 方法可以將請求參數轉為字典
實例:
```text
from urllib.parse import parse_qs
query = '''f=json&mock=&uin=777&key=777&pass_ticket=nFLy3qzW6g8xVh%25252FRdSuoEMZn%25252BYrRjEh0fsybociYtgE%25253D&wxtoken=777&devicetype=android-26&clientversion=26060739&appmsg_token=966_3pMS7R2ZHEtCjbLZ3O0EDgaTpZ9B-N7GrMG3lOqeNFz9EH9p3dcgPHSiCjE~&x5=1&f=json'''
print(parse_qs(query))
```
運行結果:
```text
{'f': ['json', 'json'], 'uin': ['777'], 'key': ['777'], 'pass_ticket': ['nFLy3qzW6g8xVh%252FRdSuoEMZn%252BYrRjEh0fsybociYtgE%253D'], 'wxtoken': ['777'], 'devicetype': ['android-26'], 'clientversion': ['26060739'], 'appmsg_token': ['966_3pMS7R2ZHEtCjbLZ3O0EDgaTpZ9B-N7GrMG3lOqeNFz9EH9p3dcgPHSiCjE~'], 'x5': ['1']}
```
## 9.parse\_qsl\(\)
parse\_qsl\(\) 方法可以將參數轉化為元組組成的列表
實例:
```text
from urllib.parse import parse_qsl
query = '''f=json&mock=&uin=777&key=777&pass_ticket=nFLy3qzW6g8xVh%25252FRdSuoEMZn%25252BYrRjEh0fsybociYtgE%25253D&wxtoken=777&devicetype=android-26&clientversion=26060739&appmsg_token=966_3pMS7R2ZHEtCjbLZ3O0EDgaTpZ9B-N7GrMG3lOqeNFz9EH9p3dcgPHSiCjE~&x5=1&f=json'''
print(parse_qsl(query))
```
運行結果:
```text
[('f', 'json'), ('uin', '777'), ('key', '777'), ('pass_ticket', 'nFLy3qzW6g8xVh%252FRdSuoEMZn%252BYrRjEh0fsybociYtgE%253D'), ('wxtoken', '777'), ('devicetype', 'android-26'), ('clientversion', '26060739'), ('appmsg_token', '966_3pMS7R2ZHEtCjbLZ3O0EDgaTpZ9B-N7GrMG3lOqeNFz9EH9p3dcgPHSiCjE~'), ('x5', '1'), ('f', 'json')]
```
## 10. quote\(\)
quote\(\) 方法可以將內容轉化為 URL 編碼的格式,有時候 URL 中帶有中文參數的時候可能導致亂碼的問題,所以我們可以用這個方法將中文字符轉化為 URL 編碼
實例:
```text
from urllib.parse import quote
wd = "貓"
url = "https://www.baidu.com/s?wd="+quote(wd)
print(url)
```
運行結果:
```text
https://www.baidu.com/s?wd=%E7%8C%AB
```
## 11.unquote\(\)
unquote\(\) 方法,它可以進行 URL 解碼
實例:
```text
from urllib.parse import unquote
url = "https://www.baidu.com/s?wd=%E7%8C%AB"
print(unquote(url))
```
運行結果:
```text
https://www.baidu.com/s?wd=貓
```
- 介紹
- 1.開發環境配置
- 1.1 python3的安裝
- 1.1.1 windows下的安裝
- 1.1.2 Linux下的安裝
- 1.1.3 Mac下的安裝
- 1.2 請求庫的安裝
- 1.2.1 requests的安裝
- 1.2.2 selenium的安裝
- 1.2.3 ChromeDriver的安裝
- 1.2.4 GeckoDriver 的安裝
- 1.2.5 PhantomJS的安裝
- 1.2.6 aiohttp的安裝
- 1.3 解析庫的安裝
- 1.3.1 lxml的安裝
- 1.3.2 Beautiful Soup的安裝
- 1.3.3 pyquery的安裝
- 1.3.4 tesserocr的安裝
- 1.4 數據庫的安裝
- 1.4.1 MySQL的安裝
- 1.4.2 MongoDB的安裝
- 1.4.3 Redis的安裝
- 1.5 存儲庫的安裝
- 1.5.1 PyMySQL的安裝
- 1.5.2 PyMongo的安裝
- 1.5.3 redis-py的安裝
- 1.5.4 RedisDump的安裝
- 1.6 Web庫的安裝
- 1.6.1 Flask的安裝
- 1.6.2 Tornado的安裝
- 1.7 App爬取相關庫的安裝
- 1.7.1 Charles的安裝
- 1.7.2 mitmproxy的安裝
- 1.7.3 Appium的安裝
- 1.8 爬蟲框架的安裝
- 1.8.1 pyspider的安裝
- 1.8.2 Scrapy的安裝
- 1.8.3 Scrapy-Splash的安裝
- 1.8.4 ScrapyRedis的安裝
- 1.9 布署相關庫的安裝
- 1.9.1 Docker的安裝
- 1.9.2 Scrapyd的安裝
- 1.9.3 ScrapydClient的安裝
- 1.9.4 ScrapydAPI的安裝
- 1.9.5 Scrapyrt的安裝
- 1.9.6-Gerapy的安裝
- 2.爬蟲基礎
- 2.1 HTTP 基本原理
- 2.1.1 URI和URL
- 2.1.2 超文本
- 2.1.3 HTTP和HTTPS
- 2.1.4 HTTP請求過程
- 2.1.5 請求
- 2.1.6 響應
- 2.2 網頁基礎
- 2.2.1網頁的組成
- 2.2.2 網頁的結構
- 2.2.3 節點樹及節點間的關系
- 2.2.4 選擇器
- 2.3 爬蟲的基本原理
- 2.3.1 爬蟲概述
- 2.3.2 能抓怎樣的數據
- 2.3.3 javascript渲染的頁面
- 2.4 會話和Cookies
- 2.4.1 靜態網頁和動態網頁
- 2.4.2 無狀態HTTP
- 2.4.3 常見誤區
- 2.5 代理的基本原理
- 2.5.1 基本原理
- 2.5.2 代理的作用
- 2.5.3 爬蟲代理
- 2.5.4 代理分類
- 2.5.5 常見代理設置
- 3.基本庫使用
- 3.1 使用urllib
- 3.1.1 發送請求
- 3.1.2 處理異常
- 3.1.3 解析鏈接
- 3.1.4 分析Robots協議
- 3.2 使用requests
- 3.2.1 基本用法
- 3.2.2 高級用法
- 3.3 正則表達式
- 3.4 抓取貓眼電影排行
- 4.解析庫的使用
- 4.1 使用xpath
- 4.2 使用Beautiful Soup
- 4.3 使用pyquery
- 5.數據存儲
- 5.1 文件存儲
- 5.1.1 TXT 文件存儲
- 5.1.2 JSON文件存儲
- 5.1.3 CSV文件存儲
- 5.2 關系型數據庫存儲
- 5.2.1 MySQL的存儲
- 5.3 非關系數據庫存儲
- 5.3.1 MongoDB存儲
- 5.3.2 Redis存儲
- 6.Ajax數據爬取
- 6.1 什么是Ajax
- 6.2 Ajax分析方法
- 6.3 Ajax結果提取
- 6.4 分析Ajax爬取今日頭條街拍美圖
- 7.動態渲染頁面爬取
- 7.1 Selenium的使用
- 7.2 Splash的使用
- 7.3 Splash負載均衡配置
- 7.4 使用selenium爬取淘寶商品
- 8.驗證碼的識別
- 8.1 圖形驗證碼的識別
- 8.2 極驗滑動驗證碼的識別
- 8.3 點觸驗證碼的識別
- 8.4微博宮格驗證碼的識別
- 9.代理的使用
- 9.1 代理的設置
- 9.2 代理池的維護
- 9.3 付費代理的使用
- 9.4 ADSL撥號代理
- 9.5 使用代理爬取微信公總號文章
- 10.模擬登錄
- 10.1 模擬登陸并爬去GitHub
- 10.2 Cookies池的搭建
- 11.App的爬取
- 11.1 Charles的使用
- 11.2 mitmproxy的使用
- 11.3 mitmdump“得到”App電子書信息
- 11.4 Appium的基本使用
- 11.5 Appnium爬取微信朋友圈
- 11.6 Appium+mitmdump爬取京東商品
- 12.pyspider框架的使用
- 12.1 pyspider框架介紹
- 12.2 pyspider的基本使用
- 12.3 pyspider用法詳解
- 13.Scrapy框架的使用
- 13.1 scrapy框架介紹
- 13.2 入門
- 13.3 selector的用法
- 13.4 spider的用法
- 13.5 Downloader Middleware的用法
- 13.6 Spider Middleware的用法
- 13.7 Item Pipeline的用法
- 13.8 Scrapy對接Selenium
- 13.9 Scrapy對接Splash
- 13.10 Scrapy通用爬蟲
- 13.11 Scrapyrt的使用
- 13.12 Scrapy對接Docker
- 13.13 Scrapy爬取新浪微博
- 14.分布式爬蟲
- 14.1 分布式爬蟲原理
- 14.2 Scrapy-Redis源碼解析
- 14.3 Scrapy分布式實現
- 14.4 Bloom Filter的對接
- 15.分布式爬蟲的部署
- 15.1 Scrapyd分布式部署
- 15.2 Scrapyd-Client的使用
- 15.3 Scrapyd對接Docker
- 15.4 Scrapyd批量部署
- 15.5 Gerapy分布式管理
- 微信公總號文章實戰
- 源碼
- other