網站首頁 編程語言 正文
一、簡介
urllib
庫,它是 Python
內置的 HTTP
請求庫,不需要額外安裝即可使用,它包含四個模塊:
`request` 請求模塊,提供最基本的 `HTTP` 請求處理。 `parse` 工具模塊,提供處理 `url` 的很多方法:拆分、解析、合并等等。 `error` 異常處理模塊,如果出現請求錯誤,可以捕獲這些錯誤,保證程序不會意外終止。 `robotparser` 模塊,主要用來識別網站的 `robots.txt` 文件,判斷哪些網站可以爬取,用的比較少。
二、 request 模塊
1、urlopen
:打開一個指定 URL
,然后使用 read()
獲取網頁的 HTML
實體代碼。
# 使用 urllib import urllib.request # 1、定義一個 url url = 'http://www.baidu.com' # 2、模擬瀏覽器向服務器發送請求 response = urllib.request.urlopen(url) # 3、獲取響應數據中的頁面源碼(注意:read() 返回的是字節形式的二進制數據,返回數據會被 b'xxx' 進行包裹) content = response.read() # 4、輸出二進制數據 content print(content) # 輸出結果:b'<html>\r\n<head>\r\n\t<script>\r\n\t\tlocation.replace(location.href.replace("https://","http://"));\r\n\t</script>\r\n</head>\r\n<body>\r\n\t<noscript><meta http-equiv="refresh" content="0;url=http://www.baidu.com/"></noscript>\r\n</body>\r\n</html>' # 5、將二進制數據轉成字符串,這里需要網頁對應的編碼格式(例如:<meta http-equiv="Content-Type" content="text/html;charset=utf-8">),charset= 的就是編碼格式 utf-8 content = content.decode('utf-8') # 6、輸出字符串 content print(content)
2、response
:響應的數據對象 HTTPResponse
類型
# 使用 urllib import urllib.request # 1、定義一個 url url = 'http://www.baidu.com' # 2、模擬瀏覽器向服務器發送請求 response = urllib.request.urlopen(url) # response 是 http.client.HTTPResponse 類型 print(type(response)) # read 方法是按照一個字節一個字節的去讀取內容 content = response.read() print(content) # read 方法可以指定讀取多少個字節 content = response.read(50) print(content) # 讀取一行 content = response.readline() print(content) # 讀取所有行 content = response.readlines() print(content) # 獲取狀態碼 print(response.getcode()) # 獲取訪問的鏈接地址 print(response.geturl()) # 獲取 headers print(response.getheaders())
3、Request
:自定義請求對象
# 使用 urllib import urllib.request # url 的組成 # https://www.baidu.com/s?wd=123 # 協議 主機 端口號 路徑 參數 錨點 # http/https www.baidu.com 80 s wd # # http 80 # https 443 # mysql 3306 # oracle 1521 # redis 6379 # mongdb 27017 # 1、定義一個 https 的 url url = 'https://www.baidu.com' # 2、模擬瀏覽器向服務器發送請求 response = urllib.request.urlopen(url) # 3、獲取內容字符串 content = response.read().decode('utf-8') # 4 會發現直接這么拿回來的數據不完整,這就是反扒的其中一種,代表給到服務器識別的信息不完整,比如 header 頭里面的請求信息缺少。 print(content) # 解決方式: # 定義 header headers = { # UA 最基本的防爬識別 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36' } # 1、定義一個 https 的 url url = 'https://www.baidu.com' # 2、定義一個 Request 對象,urlopen 方法并不能直接帶 header。 # 細節:為什么這里需要寫 url=url 而有的地方不需要?因為 Request 構造方法傳參順序問題 Request(url, data=None, headers={} ...) request = urllib.request.Request(url=url, headers=headers) # 3、模擬瀏覽器向服務器發送請求 response = urllib.request.urlopen(request) # 3、獲取內容字符串 content = response.read().decode('utf-8') # 4 輸出 print(content)
4、urlretrieve
:下載(例如:圖片、視頻、網頁源碼…)
# 使用 urllib import urllib.request # 下載網頁 url = 'http://www.baidu.com' # 參數1:頁面地址,參數2:文件名稱(或路徑與名稱,例如:./test/baidu.html、baidu.html,不指定路徑默認當前) urllib.request.urlretrieve(url, 'baidu.html') # 下載圖片 url = 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic1.win4000.com%2Fwallpaper%2F8%2F55402f62682e3.jpg&refer=http%3A%2F%2Fpic1.win4000.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1670904201&t=2dc001fbd959432efe8b8ee0792589ba' # 參數1:頁面地址,參數2:文件名稱(或路徑與名稱,例如:./test/baidu.html、baidu.html,不指定路徑默認當前) urllib.request.urlretrieve(url, 'dzm.jpg')
二、 parse 模塊
1、quote
:(GET)參數進行 unicode
編碼
quote
會對參數進行 unicode
編碼,但是得一個一個參數的進行轉換,在進行拼接,在多個參數時使用起來比較麻煩。
# 使用 urllib import urllib.request # 定義 header headers = { # UA 最基本的防爬識別 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36' } # 1、定義一個 https 的 url # 這種中文寫法會報錯,因為 ascii 檢索不到 # url = 'https://www.baidu.com/s?wd=卡爾特斯CSDN' # 也就是需要 `卡爾特斯CSDN` 變成 unicode 編碼格式,例如這樣: # url = 'https://www.baidu.com/s?wd=%E5%8D%A1%E5%B0%94%E7%89%B9%E6%96%AFCSDN' # 準備基礎地址(不能整個鏈接去進行 quote 轉換)(GET) url = 'https://www.baidu.com/s?wd=' # 通過 urllib.parse.quote() 進行轉換 wd = urllib.parse.quote('卡爾特斯CSDN') # print(wd) # %E5%8D%A1%E5%B0%94%E7%89%B9%E6%96%AFCSDN # 拼接起來 url = url + wd # 2、定義一個 Request 對象,urlopen 方法并不能直接帶 header。 # 細節:為什么這里需要寫 url=url 而有的地方不需要?因為 Request 構造方法傳參順序問題 Request(url, data=None, headers={} ...) request = urllib.request.Request(url=url, headers=headers) # 3、模擬瀏覽器向服務器發送請求 response = urllib.request.urlopen(request) # 3、獲取內容字符串 content = response.read().decode('utf-8') # 4 輸出 print(content)
2、urlencode
:(GET)參數進行 unicode
編碼
urlencode
會對多個參數進行 unicode
編碼。
# 使用 urllib import urllib.request # 定義 header headers = { # UA 最基本的防爬識別 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36' } # 1、定義一個 https 的 url # 這種中文寫法會報錯,因為 ascii 檢索不到 # url = 'https://www.baidu.com/s?wd=卡爾特斯CSDN&sex=男' # 也就是需要 `卡爾特斯CSDN` 與 `男` 變成 unicode 編碼格式,例如這樣: # url = 'https://www.baidu.com/s?wd=%E5%8D%A1%E5%B0%94%E7%89%B9%E6%96%AFCSDN&sex=%E7%94%B7' # 準備基礎地址(不能整個鏈接去進行 quote 轉換)(GET) url = 'https://www.baidu.com/s?' # 參數 params = { 'wd': '卡爾特斯CSDN', 'sex': '男' } # 通過 urllib.parse.urlencode() 進行轉換(多個參數) str = urllib.parse.urlencode(params) # print(str) # wd=%E5%8D%A1%E5%B0%94%E7%89%B9%E6%96%AFCSDN&sex=%E7%94%B7 # 通過 urllib.parse.quote() 進行轉換(單個參數) # wd = urllib.parse.urlencode('卡爾特斯CSDN') # print(wd) # %E5%8D%A1%E5%B0%94%E7%89%B9%E6%96%AFCSDN # 拼接起來 url = url + str # 2、定義一個 Request 對象,urlopen 方法并不能直接帶 header。 # 細節:為什么這里需要寫 url=url 而有的地方不需要?因為 Request 構造方法傳參順序問題 Request(url, data=None, headers={} ...) request = urllib.request.Request(url=url, headers=headers) # 3、模擬瀏覽器向服務器發送請求 response = urllib.request.urlopen(request) # 3、獲取內容字符串 content = response.read().decode('utf-8') # 4 輸出 print(content)
2、urlencode
:(POST)參數進行 unicode
編碼,附:Python爬蟲Xpath定位數據的兩種方法
# 使用 urllib import urllib.request # 使用 json import json # 定義 header headers = { # UA 最基本的防爬識別 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36' } # 請求地址(POST) url = 'https://fanyi.baidu.com/sug' # 參數 params = { 'kw': '名稱' } # post 請求,參數不能進行拼接,需放到請求對象指定的參數對象中 # 通過 urllib.parse.urlencode() 進行轉換(多個參數) # str = urllib.parse.urlencode(params) # 直接使用轉換的參數字符串會報錯:POST data should be bytes, an iterable of bytes, or a file object. It cannot be of type str. # request = urllib.request.Request(url=url, data=str, headers=headers) # 上面直接使用參數字符串會報錯,是因為 post 請求參數必須要要進行編碼,指定編碼格式 data = urllib.parse.urlencode(params).encode('utf-8') # 模擬瀏覽器向服務器發送請求 request = urllib.request.Request(url=url, data=data, headers=headers) # 模擬瀏覽器向服務器發送請求 response = urllib.request.urlopen(request) # 獲取內容字符串 content = response.read().decode('utf-8') # 將字符串轉成 json obj = json.loads(content) # 輸出 json print(obj)
三、 error 模塊(URLError 與 HTTPError)
1、HTTPError
類是 URLError
類的子類。
2、導入包分別是:urllib.error.URLError
、urllib.error.HTTPError
。
3、通過 urllib
發送請求的時候,有可能發送失敗,可以通過 try-except
進行異常捕獲,異常有兩類:URLError
與 HTTPError
類。
# 使用 urllib import urllib.request # 使用 json import json # 定義 header headers = { # UA 最基本的防爬識別 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36' } # 請求地址(POST) url = 'https://fanyi.baidu.com/sug' # 參數 params = { 'kw': '名稱' } # post 請求,參數不能進行拼接,需放到請求對象指定的參數對象中 # 通過 urllib.parse.urlencode() 進行轉換(多個參數) # str = urllib.parse.urlencode(params) # 直接使用轉換的參數字符串會報錯:POST data should be bytes, an iterable of bytes, or a file object. It cannot be of type str. # request = urllib.request.Request(url=url, data=str, headers=headers) # 上面直接使用參數字符串會報錯,是因為 post 請求參數必須要要進行編碼,指定編碼格式 data = urllib.parse.urlencode(params).encode('utf-8') # 模擬瀏覽器向服務器發送請求 request = urllib.request.Request(url=url, data=data, headers=headers) # 模擬瀏覽器向服務器發送請求 response = urllib.request.urlopen(request) # 獲取內容字符串 content = response.read().decode('utf-8') # 將字符串轉成 json obj = json.loads(content) # 輸出 json print(obj)
四、Handler 處理器(IP 代理)
五、xppath 使用
原文鏈接:https://blog.csdn.net/zz00008888/article/details/127867808
相關推薦
- 2023-11-23 pyside6兩個按鈕,一個控制子線程的開始,暫停,。一個控制子線程結束
- 2023-03-26 TypeScript?基本數據類型實例詳解_其它
- 2023-01-06 Linux下find?命令的?7?種用法_linux shell
- 2022-10-03 Flutter之可滾動組件子項緩存?KeepAlive詳解_Android
- 2022-11-13 Elasticsearch6.2服務器升配后的bug(避坑指南)_服務器其它
- 2023-02-25 C++命名空間using?namespace?std是什么意思_C 語言
- 2023-05-26 keras.layers.Layer中無法定義name的問題及解決_python
- 2022-12-23 Python?tensorflow與pytorch的浮點運算數如何計算_python
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支