/

Python,創建網路請求

Python,創建網路請求

Python提供了urllib標準庫包來創建網路請求。

使用以下代碼創建請求:

1
2
3
4
5
6
7
from urllib import request
url = 'https://dog.ceo/api/breeds/list/all'

response = request.urlopen(url)
content = response.read()

print(content)

你也可以使用with語句來簡化:

1
2
3
4
5
6
7
from urllib import request
url = 'https://dog.ceo/api/breeds/list/all'

with request.urlopen(url) as response:
content = response.read()

print(content)

響應是一個字節序列,你會注意到響應被包裹在b''字符串中:

1
b'{"message":{"affenpinscher":[],"african":[],"airedale":[],"akita":[],"appenzeller":[],"australian":["shepherd"],"basenji":[],"beagle":[],"bluetick":[],"borzoi":[],"bouvier":[],"boxer":[],"brabancon":[],"briard":[],"buhund":["norwegian"],"bulldog":["boston","english","french"]},"status":"success"}'

使用content.decode('utf-8')將其解碼為UTF-8編碼的字符串。

這裡是從我的網站flavicopes.com獲取HTML內容的例子:

1
2
3
4
5
6
7
8
from urllib import request

url = 'https://flaviocopes.com'

with request.urlopen(url) as response:
content = response.read().decode('utf-8')

print(content)

你可以使用json標準庫模塊將響應解析為JSON:

1
2
3
4
5
6
7
8
9
10
from urllib import request
import json

url = 'https://dog.ceo/api/breeds/list/all'

with request.urlopen(url) as response:
content = response.read()

data = json.loads(content)
print(data['status'])

如果你需要指定查詢參數,使用urllib.parse方法構建查詢字符串:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from urllib import request, parse
url = 'https://api.thecatapi.com/v1/images/search'

parms = {
'limit' : 5,
'page' : 1,
'order' : 'Desc'
}

querystring = parse.urlencode(parms)

with request.urlopen(url + '?' + querystring) as response:
content = response.read().decode('utf-8')

print(content)

這就是內置的urllib包。

爲了方便起見,你可能想使用requests包,它不是Python標準庫的一部分,但相當受歡迎。

tags: [“Python”, “網路請求”, “urllib”, “requests”]