文章目錄
- 系列文章
- 1、導入urllib庫
- 2、get方式通路
- 3、post方式通路
- 4、逾時處理
- 5、網頁相關資訊
- 6、模拟浏覽器
系列文章
Python 學習 01 —— Python基礎
Python 庫學習 —— urllib 學習
Python 庫學習 —— BeautifulSoup4學習
Python 庫學習 —— Re 正規表達式
Python 學習 02 —— Python爬蟲
urllib庫主要用于操作網頁URL并對網頁内容進行抓取,通常我們用Python進行爬蟲會用到。這裡對部分功能進行簡單說明以便後面進行爬蟲。
1、導入urllib庫
# 由于我們爬蟲并不需要用到整個urllib,是以下面僅導入部分需要的
import urllib.request # 用于發起請求
import urllib.parse # 用于解析url
import urllib.error # 導入可能抛出的異常以便捕獲
# 目前版本針對https需要安全證書,是以需要導入ssl并執行下面語句
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
2、get方式通路
# 使用urlopen()預設使用get請求,傳回一個HTML
response = urllib.request.urlopen("http://www.baidu.com")
# read()是讀取整個HTML,此外還有readline()讀取一行,readlines()讀取所有并傳回清單
# decode()将内容解碼為utf-8
print(response.read().decode("utf-8"))
運作結果:就是百度首頁HTML源碼
3、post方式通路
# post請求可以攜帶表單資料
# 需要将資料data進行解析。先利用parse的urlencode将其編碼,再利用bytes将其轉為utf-8位元組流。
data = bytes(urllib.parse.urlencode({"username": "小白", "password": "123456"}), encoding="utf-8")
# http://httpbin.org/post是一個HTTP測試網站
response = urllib.request.urlopen("http://httpbin.org/post", data=data)
print(response.read().decode("utf-8"))
運作結果:
說明一下:
這裡使用的網址是
http://httpbin.org/post
,它是由httpbin提供的測試網址。
我們可以利用裡面提供的方法對我們的請求進行測試,例如這裡使用了它提供的post請求。
當我們點選
Try it out
,然後點選
Excute
後,實際上就是浏覽器對連結
http://httpbin.org/post
進行了POST請求,而下面
Response body
就是伺服器給我們浏覽器的響應。
4、逾時處理
現實中的爬蟲可能由于網絡波動或是被網站阻止等意外情況,導緻速度很慢之類的,是以對請求時間進行限制,當超過某個時間就先跳過目前爬取。這隻需要添加一個參數即可。
# 逾時處理(使用get測試):利用timeout參數設定為0.01秒逾時,逾時會抛出URLError異常。
try:
response = urllib.request.urlopen("http://httpbin.org/get", timeout=0.01)
print(response.read().decode("utf-8"))
except urllib.error.URLError as e:
print("逾時")
5、網頁相關資訊
針對每個請求,伺服器都會有響應的狀态碼、響應頭部等,我們可以從傳回值中直接讀取。
# 擷取網頁資訊
response = urllib.request.urlopen("http://baidu.com")
print(response.status) # 狀态碼 200 表示成功,404 表示找不到網頁,418 表示拒絕爬蟲
print(response.getheaders()) # 擷取響應頭
print(response.getheader("Server")) # 擷取響應頭某個參數
6、模拟浏覽器
# 模拟浏覽器
url = "https://www.douban.com"
# 這是添加請求頭部用以模拟浏覽器
headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36"
}
# 豆瓣是Get方式
# 用POST是這樣:urllib.request.Request(url=url, data=data, headers=headers, method="POST")
req = urllib.request.Request(url=url, headers=headers) # 預設是Get
response = urllib.request.urlopen(req)
print(response.read().decode("utf-8"))
注意:https的請求需要導入
ssl
子產品,并執行
ssl._create_default_https_context = ssl._create_unverified_context
說明一下:
請求頭部裡包含的是我們對目标URL發起請求所提供的資訊,其中
User-Agent
表示使用者代理,即我們是用什麼來通路的,我們如果不添加headers的
User-Agent
就會暴露我們是
python-urllib 3.9
爬蟲。