共計(jì) 788 個(gè)字符,預(yù)計(jì)需要花費(fèi) 2 分鐘才能閱讀完成。
要在 Python 中爬取本地 服務(wù)器 數(shù)據(jù),可以使用 Python 的內(nèi)置模塊 urllib
或requests
。以下是使用 urllib
模塊的示例代碼:
import urllib.request
# 創(chuàng)建一個(gè)請(qǐng)求對(duì)象
request = urllib.request.Request('http://localhost:8000/api/data')
# 發(fā)送請(qǐng)求并獲取響應(yīng)
response = urllib.request.urlopen(request)
# 讀取響應(yīng)內(nèi)容
data = response.read()
# 解碼響應(yīng)內(nèi)容
decoded_data = data.decode('utf-8')
# 輸出解碼后的內(nèi)容
print(decoded_data)
以上代碼通過創(chuàng)建一個(gè) urllib.request.Request
對(duì)象來指定要訪問的 URL,然后使用 urllib.request.urlopen()
方法發(fā)送請(qǐng)求并獲取響應(yīng)。最后,使用 response.read()
方法讀取響應(yīng)內(nèi)容,并使用 .decode()
方法解碼內(nèi)容。
如果你已經(jīng)安裝了 requests
模塊,你也可以使用 requests
模塊來實(shí)現(xiàn)相同的功能。以下是使用 requests
模塊的示例代碼:
import requests
# 發(fā)送請(qǐng)求并獲取響應(yīng)
response = requests.get('http://localhost:8000/api/data')
# 獲取響應(yīng)內(nèi)容
data = response.text
# 輸出響應(yīng)內(nèi)容
print(data)
以上代碼使用 requests.get()
方法發(fā)送 GET 請(qǐng)求并獲取響應(yīng)。然后,使用 response.text
屬性獲取響應(yīng)內(nèi)容。最后,輸出響應(yīng)內(nèi)容。
需要注意的是,以上示例代碼假設(shè)本地服務(wù)器的地址是http://localhost:8000/api/data
,你需要根據(jù)你的實(shí)際情況修改 URL。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!