There is a library so simple that it makes you scream: Requests . Remember the pain you experienced using urllib
and urllib2
? Forget about them! Requests is like a caring web assistant that can achieve the most complex web interactions with the least amount of code.
The Simplest GET Request
import requests
response = requests.get('https://api.github.com')
print(response.status_code) # Print status code
print(response.text) # Print response content
This code is so simple that beginners can take off directly! In just a few lines, you can fetch web resources. requests
simplifies complex HTTP request operations into almost conversational code.
GET Request with Parameters
Sometimes, we need to pass some extra parameters. For example, for searching or filtering, Requests can handle it all:
params = {'key1': 'value1', 'key2': 'value2'}
response = requests.get('https://httpbin.org/get', params=params)
print(response.url) # You will see the automatically concatenated URL
See that? The parameters are directly appended to the URL, super convenient!
Effortless POST Requests
Sending data? Submitting forms? Requests can handle it all:
data = {'username': 'XXX', 'password': '123456'}
response = requests.post('https://httpbin.org/post', data=data)
print(response.json()) # Directly parse JSON
JSON data, form data, file uploads, Requests can handle it all easily. Say goodbye to cumbersome web requests!
Handling Various HTTP Scenarios
Want to add request headers? Set timeouts? Handle cookies? So easy!
headers = {'User-Agent': 'Mozilla/5.0'}
response = requests.get('https://www.example.com',
headers=headers,
timeout=3)
Exception Handling is No Longer a Problem
try:
response = requests.get('https://www.example.com', timeout=3)
response.raise_for_status() # Automatically check if the request was successful
except requests.exceptions.RequestException as e:
print(f"Network request error: {e}")
Friendly Reminder : Network requests, being a “prone to error” area, must be handled with care!
Requests is that powerful, solving the most complex web requests with the least amount of code. Say goodbye to complexity and embrace simplicity!
Like and Share
Let money and love flow to you