How to use the requests module in Python 3.x to make HTTP requests
Overview:
When developing and building modern web applications, it is often necessary to interact with external resources, and HTTP is the most commonly used one of the agreements. Python provides many libraries to make HTTP requests, the most popular of which is the requests module. This article explains how to make HTTP requests using the requests module in Python 3.x, with code examples.
pip install requests
Using requestsSending a GET request is very simple. . Simply import the requests module, specify the target URL using the get() method, and then process the response data using the json() or text() method.
import requests url = "https://api.example.com/users" response = requests.get(url) # 获取 JSON 格式的响应数据 data = response.json() # 输出响应数据 print(data)
Sending a POST request is similar to sending a GET request, just use the post() method and specify the target URL and the data to send.
import requests url = "https://api.example.com/users" data = { "name": "John Doe", "age": 30, "email": "johndoe@example.com" } response = requests.post(url, data=data) # 输出响应码 print(response.status_code)
Sometimes the server needs additional information to handle the request correctly, such as authentication, user agent, etc. We can add request headers using the headers parameter.
import requests url = "https://api.example.com/users" headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3" } response = requests.get(url, headers=headers) # 输出响应数据 print(response.json())
In actual applications, various errors and exceptions may be encountered. We can use try/except blocks to handle these situations.
import requests url = "https://api.example.com/users" response = None try: response = requests.get(url) response.raise_for_status() # 如果请求失败,抛出异常 except requests.exceptions.HTTPError as errh: print("HTTP Error:", errh) except requests.exceptions.ConnectionError as errc: print("Error Connecting:", errc) except requests.exceptions.Timeout as errt: print("Timeout Error:", errt) except requests.exceptions.RequestException as err: print("Something went wrong:", err) if response is not None: print(response.json())
Summary:
In this article, we learned how to make HTTP requests using the requests module in Python 3.x. We learned how to send GET and POST requests and process the response data. We also learned how to add request headers and how to handle errors and exceptions. The requests module is powerful and easy to use, making it a great choice for building modern web applications.
I hope this article will help you understand how to use the requests module in Python 3.x to make HTTP requests!
The above is the detailed content of How to use the requests module to make HTTP requests in Python 3.x. For more information, please follow other related articles on the PHP Chinese website!