Python - AI 助手

Python Requests get() 方法



Python Requests 的get()方法用於向指定的URL傳送HTTP GET請求。此方法從指定的伺服器端點檢索資料。

此方法可以接受可選引數,例如用於查詢引數的params,用於自定義標頭的headers,用於請求超時的timeout和用於身份驗證的auth。

此方法返回一個Response物件,其中包含伺服器的響應資料、狀態程式碼、標頭等等。它通常用於從API或網頁獲取資料。

語法

以下是Python Requests get()方法的語法和引數:

requests.get(url, params=None, **kwargs)

引數

以下是Python Requests get()方法的引數:

  • url: 這是我們要獲取的資源的URL。
  • params(字典或位元組流,可選): 傳送到請求查詢字串中的字典或位元組流。
  • kwargs(可選): 可選引數,包括headers、cookies、authentication等。

返回值

此方法返回一個Response物件。

示例1

以下是一個基本示例,它涉及使用python requests get()方法向指定的URL傳送請求並處理響應:

import requests

response = requests.get('https://tutorialspoint.tw')
print(response.url)  

輸出

https://tutorialspoint.tw/

示例2

get()方法的'params'引數用於獲取URL的引數。此引數接受一個鍵值對字典,這些鍵值對將被編碼為URL中的查詢引數。以下是一個示例:

import requests
params = {'q': 'python requests', 'sort': 'relevance'}
response = requests.get('https://tutorialspoint.tw', params=params)
print(response.url)

輸出

https://tutorialspoint.tw/?q=python+requests&sort=relevance

示例3

requests模組透過在get()方法中指定引數'auth'來支援多種身份驗證方式。以下是一個基本的身份驗證示例:

import requests
from requests.auth import HTTPBasicAuth

# Define the URL
url = 'https://httpbin.org/basic-auth/user/pass'

# Define the credentials
username = 'user'
password = 'pass'

# Send the GET request with Basic Authentication
response = requests.get(url, auth=HTTPBasicAuth(username, password))

# Print the response status code
print(response.status_code)

# Print the response content
print(response.text)

輸出

200
{
  "authenticated": true,
  "user": "user"
}
python_modules.htm
廣告