Home Backend Development Python Tutorial How to Use Proxies in Python

How to Use Proxies in Python

Nov 16, 2024 pm 12:00 PM

How to Use Proxies in Python

If you've been working with Python for a bit, especially in the particular case of data scraping, you've probably encountered situations where you are blocked while trying to retrieve the data you want. In such a situation, knowing how to use a proxy is a handy skill to have.

In this article, we'll explore what proxies are, why they're useful, and how you can use them using the library request in Python.

What is a Proxy?

Let’s start from the beginning by defining what a proxy is.

You can think of a proxy server as a “middleman” between your computer and the internet. When you send a request to a website, the request goes through the proxy server first. The proxy then forwards your request to the website, receives the response, and sends it back to you. This process masks your IP address, making it appear as if the request is coming from the proxy server instead of your own device.

As understandable, this has a lot of consequences and uses. For example, it can be used to bypass some pesky IP restrictions, or maintain anonymity.

Why use a proxy in web scraping?

So, why proxies might be helpful while scraping data? Well, we already gave a reason before. For example, you can use them to bypass some restrictions.

So, in the particular case of web scraping, they can be useful for the following reasons:

  • Avoiding IP blocking: websites often monitor for suspicious activity, like a single IP making numerous requests in a short time. Using proxies helps distribute your requests across multiple IPs avoiding being blocked.
  • Bypassing geo-restrictions: some content is only accessible from certain locations and proxies can help you appear as if you're accessing the site from a different country.
  • Enhancing privacy: proxies are useful to keep your scraping activities anonymous by hiding your real IP address.

How to use a proxy in Python using requests

The requests library is a popular choice for making HTTP requests in Python and incorporating proxies into your requests is straightforward.

Let’s see how!

Getting Valid Proxies

First things first: you have to get valid proxies before actually using them. To do so, you have two options:

  • Free proxies: you can get proxies for free from websites like Free Proxy List. They're easily accessible but, however, they can be unreliable or slow.
  • Paid proxies: services like Bright Data or ScraperAPI provide reliable proxies with better performance and support, but you have to pay.

Using Proxies with requests

Now that you have your list of proxies you can start using them. For example, you can create a dictionary like so:

proxies = {
    'http': 'http://proxy_ip:proxy_port',
    'https': 'https://proxy_ip:proxy_port',
}
Copy after login

Now you can make a request using the proxies:

import requests

proxies = {
    'http': 'http://your_proxy_ip:proxy_port',
    'https': 'https://your_proxy_ip:proxy_port',
}

response = requests.get('https://httpbin.org/ip', proxies=proxies)
Copy after login

To see the outcome of your request, you can print the response:

print(response.status_code)  # Should return 200 if successful
print(response.text)         # Prints the content of the response
Copy after login

Note that, if everything went smoothly, the response should display the IP address of the proxy server, not yours.

Proxy Authentication Using requests: Username and Password

If your proxy requires authentication, you can handle it in a couple of ways.

Method 1: including Credentials in the Proxy URL
To include the username and password to manage authentication in your proxy, you can do so:

proxies = {
    'http': 'http://username:password@proxy_ip:proxy_port',
    'https': 'https://username:password@proxy_ip:proxy_port',
}
Copy after login

Method 2: using HTTPProxyAuth
Alternatively, you can use the HTTPProxyAuth class to handle authentication like so:

from requests.auth import HTTPProxyAuth

proxies = {
    'http': 'http://proxy_ip:proxy_port',
    'https': 'https://proxy_ip:proxy_port',
}

auth = HTTPProxyAuth('username', 'password')

response = requests.get('https://httpbin.org/ip', proxies=proxies, auth=auth)
Copy after login

How to Use a Rotating Proxy with requests

Using a single proxy might not be sufficient if you're making numerous requests. In this case, you can use a rotating proxy: this changes the proxy IP address at regular intervals or per request.

If you’d like to test this solution, you have two options: manually rotate proxies using a list or using a proxy rotation service.

Let’s see both approaches!

Using a List of Proxies

If you have a list of proxies, you can rotate them manually like so:

import random

proxies_list = [
    'http://proxy1_ip:port',
    'http://proxy2_ip:port',
    'http://proxy3_ip:port',
    # Add more proxies as needed
]

def get_random_proxy():
    proxy = random.choice(proxies_list)
    return {
        'http': proxy,
        'https': proxy,
    }

for i in range(10):
    proxy = get_random_proxy()
    response = requests.get('https://httpbin.org/ip', proxies=proxy)
    print(response.text)
Copy after login

Using a Proxy Rotation Service

Services like ScraperAPI handle proxy rotation for you. You typically just need to update the proxy URL they provide and manage a dictionary of URLs like so:

proxies = {
    'http': 'http://your_service_proxy_url',
    'https': 'https://your_service_proxy_url',
}

response = requests.get('https://httpbin.org/ip', proxies=proxies)
Copy after login

Conclusions

Using a proxy in Python is a valuable technique for web scraping, testing, and accessing geo-restricted content. As we’ve seen, integrating proxies into your HTTP requests is straightforward using the library requests.

A few parting tips when scraping data from the web:

  • Respect website policies: always check the website's robots.txt file and terms of service.
  • Handle exceptions: network operations can fail for various reasons, so make sure to handle exceptions and implement retries if necessary.
  • Secure your credentials: if you're using authenticated proxies, keep your credentials safe and avoid hardcoding them into your scripts.

Happy coding!

The above is the detailed content of How to Use Proxies in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

What are regular expressions? What are regular expressions? Mar 20, 2025 pm 06:25 PM

Regular expressions are powerful tools for pattern matching and text manipulation in programming, enhancing efficiency in text processing across various applications.

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

What are some popular Python libraries and their uses? What are some popular Python libraries and their uses? Mar 21, 2025 pm 06:46 PM

The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H

How to dynamically create an object through a string and call its methods in Python? How to dynamically create an object through a string and call its methods in Python? Apr 01, 2025 pm 11:18 PM

In Python, how to dynamically create an object through a string and call its methods? This is a common programming requirement, especially if it needs to be configured or run...

See all articles