urllib模塊

編輯本隨筆html

urllib模塊

python中自帶的一個基於爬蟲的模塊。python

做用

可使用代碼模擬瀏覽器發起請求web

子模塊

request瀏覽器

parse服務器

使用流程

  1. 指定url,url中不能存在非ASCII編碼的字符數據
  2. 針對指定url發起請求
  3. 獲取頁面數據
  4. 持久化存儲

嘗試用urllib獲取指定url代碼:cookie

#需求:獲取指定url的頁面數據
from urllib import request
#指定url地址
url="http://127.0.0.1:8888"

#對給定的url發起請求,且返回一個響應對象
response=request.urlopen(url=url)

#獲取頁面數據,即對響應對象執行read函數,返回二進制數據
page_test=response.read()

#進行持久化存儲
with open('local.html','wb') as f:
    f.write(page_test)
    print("寫入數據成功!")

url編碼處理

#需求:爬取指定詞條的數據
import urllib.request
import urllib.parse

#指定url
#url特性:url不能夠存在非ASCII編碼的字符數據
url="https://www.sogou.com/web?query="
world=urllib.parse.quote("人民幣")
url+=world

#發起請求
response=rullib.request.urlopen(rul=rul)
#獲取頁面數據

page_text=response.read()
print(page_text)
with open('renminbi.html','wb') as fp:
    fp.write(page_text)

UA身份假裝

反爬機制:負載均衡

  1. 檢查請求UA,若是請求的UA爲爬蟲程序,拒絕提供網站數據

反反爬機制:函數

  1. 假裝爬蟲程序的請求UA

User-Agent:請求載體的身份標識post

import urllib.request
url="https://www.baidu.com/"

#UA請求頭假裝
headers={
    #存儲任意的請求頭信息
    "User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64; rv:64.0) Gecko/20100101 Firefox/64.0"
}
request=urllib.request.Request(url=url,headers=headers)

#發起請求
response=urllib.request.urlopen(request)

page_test=response.read()
print(page_test)

POST請求

#需求:獲取百度翻譯結果
#一、指定URL
url="https://fanyi.baidu.com/sug/"

#二、處理POST攜帶的參數
#2.1 將POST參數封裝到字典中
data={
    "kw":"歡迎"
}
#2.2 使用parse模塊中的urlencode進行編碼處理,返回的是str類型
data=urllib.parse.urlencode(data)

#2.3 將步驟2的編碼結果轉換成byte類型
data=data.encode()

#三、發起post請求,data參數表示通過處理以後的post請求攜帶的參數
response=urllib.request.urlopen(url=url,data=data)

response.read()

urllib模塊高級操做

一、代理操做網站

一些網站會有相應的反爬蟲措施,例如檢測某一段時間某個IP的訪問次數,若是訪問頻率太大,可能會禁用這個IP的訪問。因此咱們須要設置代理IP,每隔一段時間換一個代理IP。

代理分類:

  • 正向代理:代理客戶端獲取數據,正向代理是爲了保護客戶端防止被追究責任
  • 反向代理:代理服務器提供數據,爲了保護服務器或負責負載均衡
#需求:經過代理的方式爬取數據
from urllib import request,parse

#一、建立處理對象,在內部封裝代理ip和端口
handler=urllib.request.ProxyHeadler(proxies={"http":"61.128.128.68:8888"})
#二、建立一個opener對象,而後使用該對象發起請求
opener=urllib.request.build_opener(handler)

url="http://www.baidu.com/s?ie=UTF-8&wd=ip"

headers={
    "User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64; rv:64.0) Gecko/20100101 Firefox/64.0"
}
#構建request對象
request=urllib.request.Request(url=url,headers=headers)
#經過自定義的opener發起open請求
response=opener.open(request)

with open('daili_get.html','wb') as f:
    f.write(response.read())

二、cookie操做

#需求:使用cookiejar實現人人網登錄

from urllib import request,parse
from http import cookiejar

#建立一個cj,用於自動存儲cookie
cj=http.cookiejar.CookieJar()

#建立處理器對象,並攜帶上cookiejar對象
handler=request.HTTPCookieProcessor(cj)

#建立opener對象,並攜帶上cookiejar對象
opener=urllib.request.build_opener(handler)

url=""
data={}
data=parse.urlencode(data).encode()
request=request.Request(url,data=data)

#用opener發起請求,並自動保存cookie,下次再用opener訪問其餘需驗證的url便可自動驗證
response=opener.open(request)
相關文章
相關標籤/搜索