Python requests proxy login password

Отправка http запроса через прокси сервер с авторизацией Python

Прокси-сервер — это промежуточное звено в Вашем общении со всемирной паутиной.

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

Существуют различные виды прокси-серверов. Некоторые дополнительно предоставляют анонимность, некоторые элементарно служат «почтальонами» пересылающими запросы и ответы. Какие-то используют высоко производительные машины под свою деятельность, какие-то более слабые. Однако существуют ещё и такие прокси-сервера, которые за свои услуги просят денежные взносы, бесплатные же могут использовать Ваш сетевой трафик в своих целях: продавать сведения о Вашей интернет-деятельности рекламщикам для анализа усовершенствования маркетинговой политики, например. Будьте бдительны и внимательны при выборе какой использовать прокси-сервер, идеально безопасной сети не бывает.

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

Существуют прокси с авторизацией, то есть для того, чтобы взаимодействовать с данным промежуточным звеном требуется знание логина и соответствующего пароля. Также, имеются в миру и не требующие авторизации и ими можно пользоваться абсолютно свободно.

Рассмотрим как отправить запрос используя оба способа.

Программное обеспечение

Для языка программирования Python был создан один крайне полезный модуль под названием requests. Задача его скромна и крайне значима — помочь во взаимодействии с глобальной всемирной паутиной. Он не идёт из коробки для Python 3.x.x, а потому требует отдельной инсталляции. О том, как установить модуль можете прочесть здесь.

Прокси без авторизации

Рассмотрим пример использования случайного прокси-сервера не требующего авторизации. Импортируйте модуль requests, затем определите используемый прокси-сервер с используемым протоколом передачи (SOCKS4, HTTP, HTTPS, и так далее) и указанным портом, создайте запрос с прописанными ранее данными прокси-сервера, отправьте запрос и получите ответ. В ответе нас будет интересовать только статус — запрос выполнен успешно или же провалился.

Схема создания записи данных прокси-сервера и отправки запроса следующая, необходимые данные предоставляется поставщиком прокси:

  1. Создаётся ассоциативный массив, где ключом является используемый протокол. Прописывать необходимо только подходящий под Ваше соединение протокол;
  2. В качестве значения ключа ассоциативного массива указывается ip-адрес или же доменное имя прокси-сервера;
  3. В конце значения прописывается порт. После адреса ставится двоеточие без каких-либо пробелов и прописывается используемый порт;
  4. Создаёте запрос указав необходимый Вам ресурс в виде доменного имени или же ip-адреса, добавив ассоциативный массив содержащий жизненно важные данные о прокси соединении;
Читайте также:  React typescript pass component

Источник

Python Requests: How to Use & Rotate Proxies

Python Requests - How to Use & Rotate Proxies

To use proxies with Python Requests create a proxies dictionary and pass it into the proxies attribute of your request.

  import requests proxies =   'http': 'http://proxy.example.com:8080', 'https': 'http://proxy.example.com:8081', > response = requests.get('http://example.com', proxies=proxies) 

In this guide for The Python Web Scraping Playbook, we will look at how to integrate the 3 most common types of proxies into our Python Requests based web scraper.

Using proxies with the Python Requests library allows you to spread your requests over multiple IP addresses making it harder for websites to detect & block your web scrapers.

In this guide we will walk you through the 3 most common proxy integration methods and show you how to use them with Python Requests:

If you would like to know how to integrate proxies into your Python Scrapy scrapers then check out our Scrapy proxies guide here.

Need help scraping the web?

Then check out ScrapeOps, the complete toolkit for web scraping.

Using Proxy IPs With Python Requests​

Using a proxy with Python requests is very straight forward. We simply need to create a proxies dictionary and pass it into the proxies attribute of our Python Requests request.

  import requests proxies =   'http': 'http://proxy.example.com:8080', 'https': 'http://proxy.example.com:8081', > response = requests.get('http://example.com', proxies=proxies) 

This method will work for all request methods Python Requests supports: GET , POST , PUT , DELETE , PATCH , HEAD .

Proxy Authentication With Python Requests​

Some proxy IPs require authentication in the form of a username and password to use the proxy.

To add authenticate the proxy you have two options:

Add Username & Password to Proxy String​

The first option is to simply add the username and password to the proxy strings.

  import requests proxies =   'http': 'http://USERNAME:PASSWORD@proxy.example.com:8080', 'https': 'http://USERNAME:PASSWORD@proxy.example.com:8081', > response = requests.get('http://example.com', proxies=proxies) 

Pass Username & Password to Auth Parameter​

Python Requests allows you to authenicate your proxy by adding the username and password to the auth parameter.

  import requests proxies =   'http': 'http://proxy.example.com:8080', 'https': 'http://proxy.example.com:8081', > response = requests.get('http://example.com', proxies=proxies auth=('USERNAME', 'PASSWORD')) 

Using Proxies With Request Sessions​

If you are using Python Requests Sessions functionality then you will need to add your proxy in a slightly different way.

Instead of defining the proxies in our requests.get() as we’ve seen previously, we will instead intialize our Requests session object and then set it to use our proxies.

  import requests session = requests.Session() session.proxies =   'http': 'http://proxy.example.com:8080', 'https': 'http://proxy.example.com:8081', > response = session.get('http://example.com') 

Add Username & Password to Proxy String​

To authenticate our proxy then again we can either add the username and password to the proxy strings.

 session.proxies =   'http': 'http://USERNAME:PASSWORD@proxy.example.com:8080', 'https': 'http://USERNAME:PASSWORD@proxy.example.com:8081', > 

Pass Username & Password to Auth Parameter​

Or add the authentication to the session object.

 session.auth = ('USERNAME', 'PASSWORD') 

When using Python Requests Session functionality with a proxy the proxy IP address you are setting remains constant, unless you are using a proxy gateway that manages the proxy rotation on their end.

If you are using a single static proxy IP with the sessions functionality then the proxy might get blocked as every request will be using it.

The 3 Most Common Proxy Formats​

That covered the basics of integrating a proxy into Python Requests, in the next sections we will show you how to integrate Python Requests into the 3 most common proxy formats:

A couple years ago, proxy providers would sell you a list of proxy IP addresses and you would configure your scraper to rotate through these IP addresses and use a new one with each request.

However, today more and more proxy providers don’t sell raw lists of proxy IP addresses anymore. Instead providing access to their proxy pools via proxy gateways or proxy API endpoints.

We will look at how to integrate with all 3 proxy formats.

If you are looking to find a good proxy provider then check out our web scraping proxy comparison tool where you can compare the plans of all the major proxy providers.

Proxy Integration #1: Rotating Through Proxy IP List​

Here a proxy provider will normally provide you with a list of proxy IP addresses that you will need to configure your scraper to rotate through and select a new IP address for every request.

The proxy list you recieve will look something like this:

  'http://Username:Password@85.237.57.198:20000', 'http://Username:Password@85.237.57.198:21000', 'http://Username:Password@85.237.57.198:22000', 'http://Username:Password@85.237.57.198:23000', 

To integrate them into our scrapers we need to configure our code to pick a random proxy from this list everytime we make a request.

In our Python Requests scraper we could do it like this:

import requests from random import randint proxy_list = [ 'http://Username:Password@85.237.57.198:20000', 'http://Username:Password@85.237.57.198:21000', 'http://Username:Password@85.237.57.198:22000', 'http://Username:Password@85.237.57.198:23000', ] proxy_index = randint(0, len(proxy_list) - 1) proxies =   "http://": proxy_list[proxy_index], "https://": proxy_list[proxy_index], > r = requests.get(url='https://example.com/', proxies=proxies) print(r.text) 

This is a simplistic example, as when scraping at scale we would also need to build a mechanism to monitor the performance of each individual IP address and remove it from the proxy rotation if it got banned or blocked.

Proxy Integration #2: Using Proxy Gateway​

Increasingly, a lot of proxy providers aren’t selling lists of proxy IP addresses anymore. Instead, they give you access to their proxy pools via a proxy gateway.

Here, you only have to integrate a single proxy into your Python Requests scraper and the proxy provider will manage the proxy rotation, selection, cleaning, etc. on their end for you.

This is the most comman way to use residential and mobile proxies, and becoming increasingly common when using datacenter proxies too.

Here is an example of how to integrate a BrightData’s residential proxy gateway into our Python Requests scraper:

import requests proxies = ‘http’: ‘http://zproxy.lum-superproxy.io:22225’, ‘https’: ‘http://zproxy.lum-superproxy.io:22225’, > url = ‘http://example.com/’ response = requests.get(url, proxies=proxies, auth=(‘USERNAME’, ‘PASSWORD’))

As you can see, it is much easier to integrate than using a proxy list as you don’t have to worry about implementing all the proxy rotation logic.

Proxy Integration #3: Using Proxy API Endpoint​

Recently, a lot of proxy providers have started offering smart proxy APIs that take care of managing your proxy infrastructure for you by rotating proxies and headers for you so you can focus on extracting the data you need.

Here you typically, send the URL you want to scrape to their API endpoint and then they will return the HTML response to.

Although every proxy API provider has a slightly different API integration, they are all very similar and are very easy to integrate with.

Here is an example of how to integrate with the ScrapeOps Proxy Manager:

  import requests from urllib.parse import urlencode payload = 'api_key': 'APIKEY', 'url': 'https://httpbin.org/ip'> r = requests.get('https://proxy.scrapeops.io/v1/', params=urlencode(payload)) print r.text 

Here you simple send the URL you want to scrape to the ScrapeOps API endpoint in the URL query parameter, along with your API key in the api_key query parameter, and ScrapeOps will deal with finding the best proxy for that domain and return the HTML response to you.

When using proxy API endpoints it is very important to encode the URL you want to scrape before sending it to the Proxy API endpoint. As if the URL contains query parameters then the Proxy API might think that those query parameters are for the Proxy API and not the target website.

To encode your URL you just need to use the urlencode(payload) function as we’ve done above in the example.

More Web Scraping Tutorials​

So that’s how you can integrate proxies into your Python Requests scrapers.

If you would like to learn more about Web Scraping, then be sure to check out The Web Scraping Playbook.

Or check out one of our more in-depth guides:

Источник

Оцените статью