¿Cómo utilizar proxies en solicitudes de Python?

In this article, we will explore how to use the Python Requests library behind a proxy server. Developers use proxies to achieve anonymity, security, and sometimes even employ multiple proxies to prevent websites from blocking their IP addresses. Proxies also offer other benefits such as bypassing filters and censorship.
Prerequisites and Installation
Step 1: Install the Requests Library
First, ensure that the Requests library is installed in your Python environment. If it is not already installed, you can install it using pip:
pip install requests
For further reading: Crawling Web Articles via HTTP Proxy in Python
Step 2: Set Up the Proxy Server
Using a proxy in Requests is straightforward. You just need to create a dictionary containing the protocol and address of the proxy server you want to use. For example:
proxies = {
"http": "http://10.10.1.10:3128",
"https": "https://10.10.1.10:1080",
}
Here, the `http` key corresponds to the proxy server address for HTTP requests, and the `https` key corresponds to the proxy server address for HTTPS requests. Note that you need to replace the proxy server's IP address and port number with your actual settings.
Step 3: Send a Request
Once the proxy is set up, you can pass it as a parameter when sending a request with Requests. Here is an example of sending a GET request using a proxy:
import requests
url = 'http://example.com'
proxies = {
"http": "http://10.10.1.10:3128",
"https": "https://10.10.1.10:1080",
}
response = requests.get(url, proxies=proxies)
print(response.text)
Step 4: Handle Exceptions
When using proxies, you may encounter network connection issues or problems with the proxy server. To make your application more robust, you should catch and handle possible exceptions:
import requests
from requests.exceptions import RequestException
url = 'http://example.com'
proxies = {
"http": "http://10.10.1.10:3128",
"https": "https://10.10.1.10:1080",
}
try:
response = requests.get(url, proxies=proxies)
print(response.text)
except RequestException as e:
print(f"Request failed: {e}")
Step 5: Use an Authenticated Proxy Server
If your proxy server requires authentication, you can include the username and password in the proxy address. For example:
proxies = {
"http": "http://user:[email protected]:3128",
"https": "https://user:[email protected]:1080",
}
Make sure to replace `user` and `password` with your proxy authentication details.
By following these steps, you can use the Requests library in Python to send requests through a proxy. This is very useful for web scraping, testing, and many other scenarios.
A partir de este tutorial, exploraremos más a fondo cómo administrar múltiples servidores proxy utilizando la biblioteca de solicitudes de Python e implementaremos un grupo de proxy simple. Esto es particularmente útil para situaciones en las que se necesitan cambios frecuentes de dirección IP para evitar ser bloqueado por el sitio web de destino.
Crear un grupo de proxy
La idea básica de un grupo de proxy es mantener una lista de servidores proxy y seleccionar uno al azar para distribuir el origen de las solicitudes. A continuación se explica cómo implementar un grupo de proxy básico:
Almacenar la lista de servidores proxy: puede almacenar los servidores proxy en una lista o utilizar un sistema de almacenamiento más avanzado, como una base de datos o un sistema de almacenamiento en caché.
Seleccione un proxy: elija aleatoriamente un proxy de la lista para realizar una solicitud.
Validar la eficacia del proxy: compruebe periódicamente la validez de los proxy y elimine aquellos que no sean válidos o que respondan lentamente.
solicitudes de importación
importar aleatoriamente
# Lista de proxy
lista_proxies = [
{"http": "http://10.10.1.10:3128", "https": "https://10.10.1.10:1080"},
{"http": "http://10.10.2.10:3128", "https": "https://10.10.2.10:1080"},
{"http": "http://10.10.3.10:3128", "https": "https://10.10.3.10:1080"}
]
def get_random_proxy():
devolver elección aleatoria (lista_proxies)
# Enviar solicitud usando un proxy aleatorio
URL = 'http://ejemplo.com'
proxy = get_random_proxy()
respuesta = solicitudes.get(url, proxies=proxy)
imprimir (respuesta.texto)
¿Cómo utilizar proxies en solicitudes de Python? preguntas frecuentes de la reseña
A continuación se muestra un s...
En este artículo, exploraremos...

