Руководство по использованию прокси с Requests Python

Руководство по использованию прокси с request Python для парсинга. Почему это может быть полезно при работе над проектом веб-скрапинга.
9 min read
Guide to using proxy with python request

Proxies are IP addresses from a proxy server that connect to the internet on your behalf. Instead of directly transmitting your requests to the website you visit, when you connect to the internet through a proxy, your requests are routed through the proxy server. Utilizing a proxy server is a great way to safeguard your online privacy and enhance security:

Что такое прокси

Прокси-сервер действует как компьютер-посредник, то есть ваш IP-адрес и местоположение скрываются от сайта. Это помогает защитить вас от онлайн-отслеживания, целевой рекламы и блокировки со стороны сайта, к которому вы пытаетесь получить доступ. Прокси также предлагают дополнительный уровень безопасности, шифруя ваши данные во время их передачи между вашим устройством и прокси-сервером

В этой статье вы узнаете больше о прокси и о том, как их можно использовать с requests Python. Вы также узнаете, почему это может быть полезно при парсинге веб-страниц

Why You Need Proxies When Web Scraping

Web scraping is an automated process for extracting data from websites for different purposes, including data aggregation, market research, and data analysis. However, many of these websites have restrictions that make it challenging to access the information you want.

К счастью, прокси могут помочь вам обойти ограничения на основе IP и местоположения. Например, иногда сайты предоставляют различную информацию для определенных локаций, таких как страна или штат. Если вы не находитесь в этом конкретном месте, вы не сможете получить доступ к нужной информации без прокси, который может обойти IP-адрес и изменить ваше местоположение.

In addition, most websites block the IP addresses of devices that are involved in web scraping activities. In this situation, you can implement a proxy to hide your IP address and location, making it more difficult for the website to identify and block you.

Вы также можете использовать несколько прокси одновременно, чтобы распределить действия по парсингу веб-страниц по разным IP и ускорить процесс веб-скрапинга, позволяя парсеру выполнять несколько запросов одновременно.

Now that you know how proxies can help when it comes to web scraping projects, you will learn next how to implement a proxy in your project using the Requests Python package.

How to Use a Proxy with a Python Request

In order to use a proxy with a Python request, you need to establish a new Python project on your computer to write and run the Python scripts for web scraping. Create a directory (ie web_scrape_project) where you’ll store your source code files.

All the codes for this tutorial are available in this GitHub repo.

Install Packages

После создания каталога необходимо установить следующие пакеты Python для отправки запросов на веб-страницу и сбора ссылок:

  • Requests: The Requests Python package sends HTTP requests to the website where you want to scrape the data. HTTP requests return a response object containing all response data, such as status, encoding, and content.Run the following pip command in your terminal to install the package:pip install requests
  • Beautiful Soup: Beautiful Soup is a powerful Python library that parses HTML and XML documents. You’ll use this library to navigate through the HTML document and extract all the links on Bright Data’s web page.To install Beautiful Soup, run the following pip command in your terminal:pip install beautifulsoup4

Components of Proxy IP Address

Прежде чем использовать прокси, важно понять его компоненты. Ниже мы перечислили 3 основных компонента прокси-сервера:

  1. Protocol shows the type of content you can access on the internet. The most common protocols are HTTP and HTTPS.
  2. Address shows where the proxy server is located. The address can be an IP (ie 192.167.0.1) or a DNS hostname (ie proxyprovider.com).
  3. Port used to direct traffic to the correct server process when multiple services run on a single machine (ie port number 2000).

Using all three of these components, a proxy IP address would look like this: 192.167.0.1:2000 or proxyprovider.com:2000.

How to Set Proxies Directly in Requests

Есть несколько способов установить прокси в Requests Python. В этой статье вы рассмотрите 3 разных сценария. В первом примере вы узнаете, как устанавливать прокси прямо в модуле запросов.

To start, you need to import the Requests and Beautiful Soup packages in your Python file for web scraping. Then create a directory called proxies that contains proxy server information to hide your IP address when scraping the web page. Here, you have to define both the HTTP and HTTPS connections to the proxy URL.

You also need to define the Python variable to set the URL of the web page you want to scrape the data from. For this tutorial, the URL is https://brightdata.com/

Next, you need to send a GET request to the web page using the request.get() method. The method takes two arguments: the URL of the website and proxies. Then the response from the web page is stored in the response variable.

To collect the links, use the Beautiful Soup package to parse the HTML content of the web page by passing response.content and html.parser as arguments to the BeautifulSoup() method.

Then use the find_all() method with a as an argument to find all the links on the web page. Finally, extract the href attribute of each link using the get() method.

Ниже мы показали полный исходный код для установки прокси непосредственно в запросы:

# import packages.  
import requests  
from bs4 import BeautifulSoup  
  
# Define proxies to use.  
proxies = {  
    'http': 'http://proxyprovider.com:2000',  
    'https': 'http://proxyprovider.com:2000',  
}  
  
# Define a link to the web page.  
url = "https://brightdata.com/"  
  
# Send a GET request to the website.  
response = requests.get(url, proxies=proxies)  
  
# Use BeautifulSoup to parse the HTML content of the website.  
soup = BeautifulSoup(response.content, "html.parser")  
  
# Find all the links on the website.  
links = soup.find_all("a")  
  
# Print all the links.  
for link in links:  
    print(link.get("href"))

Когда вы запускаете этот блок кода, он отправляет запрос на веб-страницу, которая была определена с помощью IP-адреса прокси. А затем возвращает ответ, в котором есть все ссылки на эту веб-страницу:

How to Set Proxies via Environment Variables

Иногда приходится использовать один и тот же прокси для всех запросов к разным веб-страницам. В этом случае имеет смысл установить переменные среды для вашего прокси.

Чтобы переменные среды для прокси были доступны каждый раз, когда вы запускаете скрипты, выполните следующую команду в своем терминале:

export HTTP_PROXY='http://proxyprovider.com:2000'  
export HTTPS_PROXY='https://proxyprovider.com:2000'

Here, the HTTP_PROXY variable sets the proxy server for HTTP requests, and the HTTPS_PROXY variable sets the proxy server for HTTPS requests.

На данный момент ваш код Python состоит из нескольких строк кода и использует переменные среды каждый раз, когда вы делаете запрос к веб-странице:

# import packages.  
import requests  
from bs4 import BeautifulSoup  
  
# Define a link to the web page.  
url = "https://brightdata.com/"  
  
# Send a GET request to the website.  
response = requests.get(url)  
  
# Use BeautifulSoup to parse the HTML content of the website.  
soup = BeautifulSoup(response.content, "html.parser")  
  
# Find all the links on the website.  
links = soup.find_all("a")  
  
# Print all the links.  
for link in links:  
    print(link.get("href"))

How to Rotate Proxies Using a Custom Method and an Array of Proxies

Ротация прокси крайне важна, поскольку сайты часто блокируют или ограничивают доступ для ботов и парсеров, когда они получают большое количество запросов с одного и того же IP-адреса. Когда это происходит, сайты могут заподозрить злонамеренную активность по парсингу и, следовательно, принять меры для блокировки или ограничения доступа.

Чередуя разные IP-адреса прокси, вы можете избежать обнаружения, представляться несколькими реальными пользователями и обойти большинство мер по борьбе с мошенничеством, которые применяет сайт.

In order to rotate proxies, you need to import a few Python libraries: Requests, Beautiful Soup, and Random.

Then create a list of proxies to use during the rotation process. This list must contain the URLs of the proxy servers in this format: http://proxyserver.com:port:

# List of proxies  
proxies = [  
    "http://proxyprovider1.com:2010", "http://proxyprovider1.com:2020",  
    "http://proxyprovider1.com:2030", "http://proxyprovider2.com:2040",  
    "http://proxyprovider2.com:2050", "http://proxyprovider2.com:2060",  
    "http://proxyprovider3.com:2070", "http://proxyprovider3.com:2080",  
    "http://proxyprovider3.com:2090"  
]


Then create a custom method called get_proxy(). This method randomly selects a proxy from the list of proxies using the random.choice() method and returns the selected proxy in dictionary format (both HTTP and HTTPS keys). You’ll use this method whenever you send a new request:

# Custom method to rotate proxies  
def get_proxy():  
    # Choose a random proxy from the list  
    proxy = random.choice(proxies)  
    # Return a dictionary with the proxy for both http and https protocols  
    return {'http': proxy, 'https': proxy}  

Once you’ve created the get_proxy() method, you need to create a loop that sends a certain number of GET requests using the rotated proxies. In each request, the get() method uses a randomly chosen proxy specified by the get_proxy() method.

После вам нужно собрать ссылки из HTML-содержимого веб-страницы с помощью пакета Beautiful Soup, как мы описали в первом примере.

В результате код Python перехватывает любые исключения, возникающие в процессе запроса, и выводит сообщение об ошибке на консоль.

Посмотрите полный исходный код для этого примера:

# import packages  
import requests  
from bs4 import BeautifulSoup  
import random  
  
# List of proxies  
proxies = [  
    "http://proxyprovider1.com:2010", "http://proxyprovider1.com:2020",  
    "http://proxyprovider1.com:2030", "http://proxyprovider2.com:2040",  
    "http://proxyprovider2.com:2050", "http://proxyprovider2.com:2060",  
    "http://proxyprovider3.com:2070", "http://proxyprovider3.com:2080",  
    "http://proxyprovider3.com:2090"  
]

  
# Custom method to rotate proxies  
def get_proxy():  
    # Choose a random proxy from the list  
    proxy = random.choice(proxies)  
    # Return a dictionary with the proxy for both http and https protocols  
    return {'http': proxy, 'https': proxy}  
  
  
# Send requests using rotated proxies  
for i in range(10):  
    # Set the URL to scrape  
    url = 'https://brightdata.com/'  
    try:  
        # Send a GET request with a randomly chosen proxy  
        response = requests.get(url, proxies=get_proxy())  
  
        # Use BeautifulSoup to parse the HTML content of the website.  
        soup = BeautifulSoup(response.content, "html.parser")  
  
        # Find all the links on the website.  
        links = soup.find_all("a")  
  
        # Print all the links.  
        for link in links:  
            print(link.get("href"))  
    except requests.exceptions.RequestException as e:  
        # Handle any exceptions that may occur during the request  
        print(e)

Using the Bright Data Proxy Service with Python

If you’re looking for a reliable, fast, and stable proxy for your web scraping tasks, then look no further than Bright Data, a web data platform that offers different types of proxies for a wide range of use cases.

Bright Data has a large network of more than 72 million residential IPs and more than 770,000 datacenter proxies that helps them provide reliable and fast proxy solutions. Their proxy offerings are designed to help you overcome the challenges of web scraping, ad verification, and other online activities that require anonymous and efficient web data collection.

Integrating Bright Data’s proxies into your Python requests is easy. For example, use the datacenter Proxies to send a request to the URL used in the previous examples.

Если у вас еще нет учетной записи, подпишитесь на бесплатную пробную версию Bright Data, а затем добавьте свои данные, чтобы создать профиль на платформе.

После этого выполните следующие шаги, чтобы создать свой первый прокси:

Click View proxy product on the welcome page to view the different types of proxy offered by Bright Data:

Типы прокси Bright Data

Select Datacenter Proxies to create a new proxy, and on the subsequent page, add your details, and save it:

Конфигурация прокси центра обработки данных

Once your proxy is created, you can view the important parameters (ie host, port, username, and password) to start accessing and using it:

Параметры прокси центра обработки данных

Once you’ve accessed your proxy, you can use the parameters information to configure your proxy URL and send a request using the Requests Python package. The format of the proxy URL is username-(session-id)-password@host:port.

Note: The session-id is a random number created by using a Python package called random.

Ниже вы можете посмотреть, как будет выглядеть ваш пример кода для установки прокси из Bright Data в запросе Python:

import requests  
from bs4 import BeautifulSoup  
import random  
  
# Define parameters provided by Brightdata  
host = 'zproxy.lum-superproxy.io'  
port = 22225  
username = 'username'  
password = 'password'  
session_id = random.random()  
  
# format your proxy  
proxy_url = ('http://{}-session-{}:{}@{}:{}'.format(username, session_id,  
                                                     password, host, port))  
  
# define your proxies in dictionary  
proxies = {'http': proxy_url, 'https': proxy_url}  
  
# Send a GET request to the website  
url = "https://brightdata.com/"  
response = requests.get(url, proxies=proxies)  
  
# Use BeautifulSoup to parse the HTML content of the website  
soup = BeautifulSoup(response.content, "html.parser")  
  
# Find all the links on the website  
links = soup.find_all("a")  
  
# Print all the links  
for link in links:  
    print(link.get("href"))

Here, you import the packages and define the proxy host, port, username, password, and session_id variables. Then you create a proxies dictionary with the http and https keys and the proxy credentials. Finally, you pass the proxies parameter to the requests.get() function to make the HTTP request and collect the links from the URL.

Вот и все! Только что вы сделали успешный запрос, используя прокси Bright Data.

Conclusion

Из этой статьи вы узнали, зачем нужны прокси и как их можно использовать для отправки запроса на веб-страницу с помощью пакета Requests Python.

С платформой веб-данных Bright Data вы можете получить надежные прокси для своего проекта, которые охватывают любую страну или город мира. Здесь предлагают несколько способов сбора необходимых данных с помощью различных типов прокси и инструментов для парсинга в соответствии с вашими потребностями.

Независимо от того, хотите ли вы собирать данные исследования рынка, отслеживать онлайн-обзоры или цены конкурентов, Bright Data имеет ресурсы, которые нужны для быстрого и эффективного выполнения работы.