python urllib庫的基本用法 1

2021-08-24 20:56:33 字數 2194 閱讀 4899

urllib.request.urlopen(url, data=none, [timeout, ]*, cafile=none, capath=none, cadefault=false, context=none)

直接用urllib.request模組的urlopen()獲取頁面,page的資料格式為bytes型別,需要decode()解碼,轉換成str型別。

from urllib import request

response = request.urlopen(r'') # httpresponse型別

page = response.read()

page = page.decode('utf-8')

urlopen返回物件提供方法:

urllib.request.request(url, data=none, headers={}, method=none)

使用request()來包裝請求,再通過urlopen()獲取頁面。

url = r''

headers =

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

page = request.urlopen(req).read()

page = page.decode('utf-8')

用來包裝頭部的資料:

urllib.request.urlopen(url, data=none, [timeout, ]*, cafile=none, capath=none, cadefault=false, context=none)

urlopen()的data引數預設為none,當data引數不為空的時候,urlopen()提交方式為post。

from urllib import request, parse

url = r''

headers =

data =

data = parse.urlencode(data).encode('utf-8')

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

page = request.urlopen(req).read()

page = page.decode('utf-8')

urllib.parse.urlencode(dict, doseq=false, safe=」, encoding=none, errors=none)

urlencode()主要作用就是將url附上要提交的資料。

data

= data

= parse.urlencode(data).encode('utf-8')

經過urlencode()轉換後的data資料為?first=true?pn=1?kd=python,最後提交的url為

first=true?pn=1?kd=python

post的資料必須是bytes或者iterable of bytes,不能是str,因此需要進行encode()編碼

page = request.urlopen(req, data=data).read()

當然,也可以把data的資料封裝在urlopen()引數中

Python urllib模組的URL編碼解碼功能

參考 我們知道,url 中是不能出現一些特殊的符號的,有些符號有特殊的用途。比如以 get 方式提交資料的時候,會在 url 中新增 key value 這樣的字串,所以在 value 中是不允許有 因此要對其進行編碼 與此同時伺服器接收到這些引數的時候,要進行解碼,還原成原始的資料。這個時候,這些...

資料庫操作基類

using system using system.componentmodel using system.collections using system.diagnostics using system.data using system.data.sqlclient using system....

MongoDB 資料庫基操

認識mongodb 進入資料庫 mongo 退出 exit 庫,集合操作 顯示所有庫 show dbs 切換 建立資料庫 use 資料庫名稱 檢視所在庫 db 刪除庫 db.dropdatabase 顯示當前資料庫的集合 show collections 建立集合 db.createcollecti...