📜  python request.txt - Python (1)

📅  最后修改于: 2023-12-03 14:46:03.575000             🧑  作者: Mango

Python Requests

Python Requests is a powerful library that allows programmers to send HTTP/1.1 requests containing data and media content to web servers and receive a response.

Installation

To install Python Requests, use the following command:

pip install requests
Basic Usage

To make a simple GET request using Requests:

import requests

response = requests.get("https://www.example.com")

print(response.text)

This code sends a GET request to https://www.example.com and prints the response content to the console.

Sending Parameters

To send parameters with a GET request:

import requests

payload = {"key1": "value1", "key2": "value2"}
response = requests.get("https://www.example.com", params=payload)

print(response.url)

This code sends a GET request to https://www.example.com with the parameters key1=value1 and key2=value2. The response URL is printed to the console.

Sending POST Data

To send POST data:

import requests

payload = {"key1": "value1", "key2": "value2"}
response = requests.post("https://www.example.com/post", data=payload)

print(response.content)

This code sends a POST request to https://www.example.com/post with the payload key1=value1 and key2=value2. The response content is printed to the console.

Uploading Files

To upload files with a POST request:

import requests

files = {"file": open("myfile.txt", "rb")}
response = requests.post("https://www.example.com/upload", files=files)

print(response.text)

This code sends a POST request to https://www.example.com/upload with the file myfile.txt. The response content is printed to the console.

Handling Errors

To handle errors:

import requests

try:
    response = requests.get("https://www.example.com/404")
    response.raise_for_status()
except requests.exceptions.HTTPError as error:
    print(error)

This code sends a GET request to https://www.example.com/404 and raises an error if the server responds with a 4xx or 5xx status code.

For more information and examples, visit the Python Requests documentation.