爬蟲 urllib基本庫的使用

2021-09-10 08:16:09 字數 1434 閱讀 8477

urllib包含了request(開啟和讀取url), error(包含request引發的異常), parse(解析url), robotparser(解析robots.txt檔案)四個用於處理url的模組。

使用urllib.request.urlopen()傳送請求:

**示例:

# -*- coding:utf-8 -*-

from urllib import request, error, parse, robotparser

import socket

# get請求

url = '' # 知識星球登入頁

res = request.urlopen(url) # 使用urllib.request模組,傳送請求後得到httpresponse物件

web_server = res.getheader('server') # 檢視執行知識星球的伺服器型別

print(web_server) # tengine(詳見

# post請求

data = bytes(parse.urlencode(), encoding='utf-8') # 使用urllib.parse模組

try:

res = request.urlopen('', data=data, timeout=0.01) # 設定超時時間為0.01s

except error.urlerror as e: # 使用urllib.error模組

if isinstance(e.reason, socket.timeout):

print('超時')

向urlopen()傳遞引數並不能構造乙個完整的請求物件,所以有了request object物件:

要構造request object物件需要用到urllib.request.request()方法:

**示例:

# -*- coding:utf-8 -*-

from urllib import request, parse

# 使用urlopen()發起請求時,傳入的引數並不能構造乙個完整的請求,所以有了urllib.request.request物件

url = ''

data = bytes(parse.urlencode(), encoding='utf-8')

headers =

req = request.request(url=url, data=data, headers=headers)

res = request.urlopen(req)

print(res.read().decode('utf-8'))

handler主要用於處理驗證,** 以及cookies。

[1]崔慶才,《python3網路開發爬蟲實戰》

[2]python官方文件urllib,

python爬蟲 urllib庫基本使用

匯入urllib from urllib import request 明確url base url 發起乙個http請求,返回乙個類檔案物件 response request.urlopen base url 獲取網頁內容 html response.read decode utf 8 將網頁寫入...

Python爬蟲 Urllib庫的基本使用

其實上面的urlopen引數可以傳入乙個request請求,它其實就是乙個request類的例項,構造時需要傳入url,data等等的內容。比如上面的兩行 我們可以這麼改寫 import urllib import requests request urllib.request.request re...

04 爬蟲 urllib2庫的基本使用

所謂網頁抓取,就是把url位址中指定的網路資源從網路流中讀取出來,儲存到本地。在python中有很多庫可以用來抓取網頁,比如urllib2。urllib2 在 python3.x 中被改為urllib.request 我們先來段 urllib2 urlopen.py 匯入urllib2 庫 impo...