python中的
library 庫簡化了製作http請求。它提供了一個乾淨,直觀的API,該API抽象了處理HTTP連接,標頭和響應中涉及的許多複雜性。要使用它,您首先需要安裝它。您可以使用pip:
<code class="“" bash> pip安裝請求</code>
安裝後,您可以開始提出請求。最常見的功能是 requests.get()
,用於從URL檢索數據。 Here's a basic example:
import requests response = requests.get("https://www.example.com") # Check the status code print(response.status_code) # Access the content print(response.text)
This code fetches the HTML content of example.com
. 響應
對象包含各種屬性,包括 status_code
(HTTP狀態代碼(如200 ok))和 text </code
(響應主體)。其他有用的屬性包括標頭
(響應標頭), json()
(用於解析JSON響應)和 content
(RAW響應字節)。錯誤處理至關重要;我們將在以後的部分中進行介紹。對於其他HTTP方法(如帖子,刪除,刪除),您使用相應的功能,例如 requests.post()
, requests.puts.put(), requests.delete() TTP方法,包括:
requests.post()
要求指定要在請求主體中發送的數據。
http狀態代碼指示HTTP請求的結果。 請求
庫使檢查和處理這些代碼變得容易。 wenders.status_code
屬性提供狀態代碼(例如,成功的200,未找到的404,內部服務器錯誤500)。您應始終檢查狀態代碼,以確保請求成功。以下是一個示例:
<代碼class =“ python”>導入請求嘗試:wersys = recesss.get('https://www.example.com&quots.compor;)worlds.raise_for_status() (f&quot;發生錯誤:{e}&qode> </code>
wendment.raise_for_status()
是一種方便的方法,如果狀態代碼指示錯誤(4xx或5xx cort client/cliers/cliers/evers/forrors),則會自動提高異常。這簡化了錯誤處理。您還可以手動檢查狀態代碼,並使用語句處理不同的情況:
<pre class="brush:php;toolbar:false"> <code class =“ python”>如果響應“未知狀態代碼:{wonsevy.status_code}&quot”)</code>
使用數據涉及使用 repacts uncess uncespss.post()</h2> <p>發送post請求,並將數據涉及</h2> </preceports.post()</post()</post()</post()</post()</codes.post()</post()</post() The data can be in various formats, such as dictionaries, lists, or files.</p><p>Here's how to send a POST request with data as a dictionary:</p><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>import requests data = {&#39;key1&#39;: &#39;value1&#39;, &#39;key2&#39;: &#39;value2&#39;} response = requests.post("https://httpbin.org/post", data=data) # httpbin.org is a useful testing site print(response.status_code) print(response.json()) # httpbin.org returns the POST data as JSON</pre><div class="contentsignin">登入後複製</div></div><p>This example sends a POST request to <code>httpbin.org/post
with the provided dictionary as the request body. httpbin.org
是測試HTTP請求的有用服務。對於發送JSON數據,請使用 JSON
參數:
<code class =“ python”>導入請求導入json data = {'key1':'value1','key2':'value2'} json())</code>
請記住使用嘗試...嘗試...
blocks和 wenders.raise_for_status()
,如上一節所示。對於發送文件,請將文件
參數與字典映射文件名一起用於文件對象。 請求
庫在處理不同數據類型的帖子請求時提供了極大的靈活性。
以上是如何使用請求在Python中提出HTTP請求?的詳細內容。更多資訊請關注PHP中文網其他相關文章!