1. urlopen( ) 方法
用於打開一個遠程的url連接,並且向這個連接發出請求,獲取響應結果。返回的結果是一個http響應對象,這個響應對象中記錄了本次http訪問的響應頭和響應體
urllib.request.urlopen 參數介紹:
urllib.request.urlopen( url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)
import urllib.request
url = 'https://www.python.org'
# 方式一
response = urllib.request.urlopen(url)
print(type(response)) # <class 'http.client.HTTPResponse'>
# 方式二
request = urllib.request.Request(url)
res = urllib.request.urlopen(url)
print(type(res)) # <class 'http.client.HTTPResponse'>
print(response.status) # 200 獲取響應狀態碼
print(response.reason) # OK
print(response.version) # 11
print(response) # 獲取響應,結果爲:<http.client.HTTPResponse object at 0x10be801d0>
print(response.headers) # 獲取響應頭
# Server: nginx
# Content-Type: text/html; charset=utf-8
# X-Frame-Options: DENY
# Via: 1.1 vegur
# Via: 1.1 varnish
# Content-Length: 48830
# Accept-Ranges: bytes
# Date: Thu, 12 Mar 2020 10:34:07 GMT
print(response.url) # https://www.python.org 獲取響應url
print(response.read()) # 獲取響應體 二進制字符串
print(response.read().decode("utf-8")) # 對響應體進行解碼
# 按行讀取
print(response.readline()) # 讀取一行
print(response.readline()) # 讀取下一行
print(response.readlines()) # 讀取多行。得到一個列表 每個元素是一行
通過結果可以發現response是一個HTTPResposne類型的對象,它主要包含的方法有read()、readinto()、getheader(name)、getheaders()、fileno()等函數和msg、version、status、reason、debuglevel、closed等屬性。
例如response.read()就可以得到返回的網頁內容,response.status就可以得到返回結果的狀態碼,如200代表請求成功,404代表網頁未找到等。
2、添加data參數的時候就是以post請求方式請求,若沒有data參數就是get請求方式
from urllib import request, parse # 用parse模塊,通過bytes(parse.urlencode())可以將post數據進行轉換並放到 # urllib.request.urlopen的data參數中。這樣就完成了一次post請求。 data = bytes(parse.urlencode({'word': 'hello'}), encoding='utf8') response = request.urlopen('http://httpbin.org/post', data=data) print(response.read())
3、timeout參數使用
在某些網絡情況不好或者服務器端異常的情況會出現請求慢的情況,或者請求異常,所以這個時候我們需要給
請求設置一個超時時間,而不是讓程序一直在等待結果。所以使用 timeout參數設置超時時間
import urllib.request response = urllib.request.urlopen('http://httpbin.org/get', timeout=1) print(response.read()) # 正常結束,控制檯顯示:socket.time : timed out response = urllib.request.urlopen('http://httpbin.org/get', timeout=0.1) print(response.read()) # 超時,控制檯顯示:urllib.error.URLErrot : <urlopen error timed out>
4、Request(url=url, data=data, method='POST') 方法
web開發中,同一個url往往可以對應若干套不同的數據(或者界面,如手機、電腦),後臺可以根據發起請求的前端的用戶代理的不同,而決定應該給前端做出什麼樣的響應,如果檢測到沒有用戶代理可以拒絕訪問。
有很多網站爲了防止程序爬蟲爬網站造成網站癱瘓,會需要攜帶一些headers頭部信息才能訪問,最長見的有user-agent參數所以需要僞裝請求頭,去訪問目標站。
urllib.ruquest.Request 參數介紹:
urllib.ruquest.Request(url=url,headers=headers,data=data,method='POST')
headers 參數使用;給請求添加頭部信息,定製自己請求網站時的頭部信息,使得請求僞裝成瀏覽器等終端
url = "http://www.baidu.com/" req = request.Request(url=url, headers={'UserAgent':'Mozilla/5.0 (Windows NT 10.0; Win64;x64)AppleWebKit/537.36 (KHTML, likeGecko)Chrome/71.0.3578.80Safari/537.36'}) res = request.urlopen(req) # 用加入了請求頭的請求對象發起請求 print(res.status) # 打印狀態碼
添加請求頭的post請求方式
from urllib import request, parse url = 'http://httpbin.org/post' headers = { 'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)', 'Host': 'httpbin.org' } dict = {'name': 'taotao'} data = bytes(parse.urlencode(dict), encoding='utf8') req = request.Request(url=url, data=data, headers=headers, method='POST') response = request.urlopen(req) print(response.read().decode('utf-8'))
添加請求頭的第二種post方式, 好處是自己可以定義一個請求頭字典,然後循環進行添加
from urllib import request, parse url = 'http://httpbin.org/post' dict = {'name': 'Germey'} data = bytes(parse.urlencode(dict), encoding='utf8') req = request.Request(url=url, data=data, method='POST') req.add_header('User-Agent', 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)') response = request.urlopen(req) print(response.read().decode('utf-8'))
5、urllib.parse模塊 方法
url解析模塊
1. urlparse( ) 方法 拆分url
URL解析函數側重於將URL字符串拆分爲其組件,或者將URL組件組合爲URL字符串
拆分的時候協議類型部分就會是scheme=“ ”指定的部分。如果url裏面已經帶了協議,scheme指定的協議不會生效
urllib.parse.urlparse(urlstring, scheme=" ", allow_fragments=True)
urlparse("www.baidu.com/index.html;user?id=5#comment",scheme="https")
from urllib.parse import urlparse, urlunparse # 對傳入的url地址進行拆分; 可以用 scheme=“ ” 指定協議類型: result = urlparse("http://www.baidu.com/index.html;user?id=5#comment") print(result) # ParseResult(scheme='http', netloc='www.baidu.com', path='/index.html', # params='user', query='id=5', fragment='comment')
2. urlunparse( ) 方法 拼接url
功能和urlparse的功能相反,它是用於拼接
data = ['http', 'www.baidu.com', 'index.html', 'user', 'a=123', 'commit'] print(urlunparse(data)) # http://www.baidu.com/index.html;user?a=123#commit
6. urlencode( ) 方法
這個方法可以將字典轉換爲url參數
對url進行編碼,因爲urllib這個框架中的url中不能出現漢字,只能出現ascii碼字符
from urllib import parse url = "https://www.baidu.com/s?" # 把參數寫成字典的形式 dic = {"ie": "utf-8", "wd": "奔馳"} # 用parse的urlencode方法編碼 parames = parse.urlencode(dic) # 將編碼以後的參數拼接到url中 url += parames print(request.urlopen(url=url))