簡體   English   中英

帶有 Python 'Requests' 模塊的代理

[英]Proxies with Python 'Requests' module

只是一個關於 Python 的優秀Requests模塊的簡短而簡單的介紹。

我似乎無法在文檔中找到變量“代理”應包含的內容。 當我向它發送一個帶有標准“IP:PORT”值的字典時,它拒絕了它要求 2 個值。 所以,我猜(因為這似乎沒有在文檔中涵蓋)第一個值是 ip 而第二個值是端口?

文檔僅提及這一點:

proxies –(可選)到代理 URL 的字典映射協議。

所以我嘗試了這個......我該怎么辦?

proxy = { ip: port}

我應該在將它們放入字典之前將它們轉換為某種類型嗎?

r = requests.get(url,headers=headers,proxies=proxy)

proxies的 dict 語法是{"protocol": "scheme://ip:port", ...} 使用它,您可以為使用httphttpsftp協議的請求指定不同(或相同)的代理:

http_proxy  = "http://10.10.1.10:3128"
https_proxy = "https://10.10.1.11:1080"
ftp_proxy   = "ftp://10.10.1.10:3128"

proxies = { 
              "http"  : http_proxy, 
              "https" : https_proxy, 
              "ftp"   : ftp_proxy
            }

r = requests.get(url, headers=headers, proxies=proxies)

requests文檔中推斷:

參數:
method -- 新請求對象的方法。
url – 新請求對象的 URL。
...
proxies –(可選)到代理 URL 的字典映射協議
...


在 linux 上,您還可以通過HTTP_PROXYHTTPS_PROXYFTP_PROXY環境變量執行此操作:

export HTTP_PROXY=10.10.1.10:3128
export HTTPS_PROXY=10.10.1.11:1080
export FTP_PROXY=10.10.1.10:3128

在 Windows 上:

set http_proxy=10.10.1.10:3128
set https_proxy=10.10.1.11:1080
set ftp_proxy=10.10.1.10:3128

您可以在此處參考代理文檔

如果您需要使用代理,您可以使用代理參數為任何請求方法配置單個請求:

import requests

proxies = {
  "http": "http://10.10.1.10:3128",
  "https": "https://10.10.1.10:1080",
}

requests.get("http://example.org", proxies=proxies)

要將 HTTP Basic Auth 與您的代理一起使用,請使用http://user:password@host.com/語法:

proxies = {
    "http": "http://user:pass@10.10.1.10:3128/"
}

我發現 urllib 有一些非常好的代碼來獲取系統的代理設置,並且它們恰好以正確的形式直接使用。 您可以像這樣使用它:

import urllib

...
r = requests.get('http://example.org', proxies=urllib.request.getproxies())

它工作得非常好,而且 urllib 也知道如何獲取 Mac OS X 和 Windows 設置。

接受的答案對我來說是一個好的開始,但我不斷收到以下錯誤:

AssertionError: Not supported proxy scheme None

對此的解決方法是在代理 url 中指定 http:// :

http_proxy  = "http://194.62.145.248:8080"
https_proxy  = "https://194.62.145.248:8080"
ftp_proxy   = "10.10.1.10:3128"

proxyDict = {
              "http"  : http_proxy,
              "https" : https_proxy,
              "ftp"   : ftp_proxy
            }

我很想知道為什么原版對某些人有效,但對我無效。

編輯:我看到主要答案現在已更新以反映這一點:)

如果你想持久化 cookie 和會話數據,你最好這樣做:

import requests

proxies = {
    'http': 'http://user:pass@10.10.1.0:3128',
    'https': 'https://user:pass@10.10.1.0:3128',
}

# Create the session and set the proxies.
s = requests.Session()
s.proxies = proxies

# Make the HTTP request through the session.
r = s.get('http://www.showmemyip.com/')

晚了8年。 但我喜歡:

import os
import requests

os.environ['HTTP_PROXY'] = os.environ['http_proxy'] = 'http://http-connect-proxy:3128/'
os.environ['HTTPS_PROXY'] = os.environ['https_proxy'] = 'http://http-connect-proxy:3128/'
os.environ['NO_PROXY'] = os.environ['no_proxy'] = '127.0.0.1,localhost,.local'

r = requests.get('https://example.com')  # , verify=False

文檔給出了一個非常清楚的代理使用示例

import requests

proxies = {
  'http': 'http://10.10.1.10:3128',
  'https': 'http://10.10.1.10:1080',
}

requests.get('http://example.org', proxies=proxies)

然而,沒有記錄的是,即使架構相同,您甚至可以為單個 url 配置代理! 當您想為要抓取的不同網站使用不同的代理時,這會派上用場。

proxies = {
  'http://example.org': 'http://10.10.1.10:3128',
  'http://something.test': 'http://10.10.1.10:1080',
}

requests.get('http://something.test/some/url', proxies=proxies)

另外, requests.get本質上是在后台使用requests.Session ,所以如果你需要更多的控制,直接使用它

import requests

proxies = {
  'http': 'http://10.10.1.10:3128',
  'https': 'http://10.10.1.10:1080',
}
session = requests.Session()
session.proxies.update(proxies)

session.get('http://example.org')

我用它來設置一個后備(默認代理)來​​處理與字典中指定的架構/url不匹配的所有流量

import requests

proxies = {
  'http': 'http://10.10.1.10:3128',
  'https': 'http://10.10.1.10:1080',
}
session = requests.Session()
session.proxies.setdefault('http', 'http://127.0.0.1:9009')
session.proxies.update(proxies)

session.get('http://example.org')

我剛剛制作了一個代理抓取器,也可以在沒有任何輸入的情況下連接相同的抓取代理:

#Import Modules

from termcolor import colored
from selenium import webdriver
import requests
import os
import sys
import time

#Proxy Grab

options = webdriver.ChromeOptions()
options.add_argument('headless')
driver = webdriver.Chrome(chrome_options=options)
driver.get("https://www.sslproxies.org/")
tbody = driver.find_element_by_tag_name("tbody")
cell = tbody.find_elements_by_tag_name("tr")
for column in cell:

        column = column.text.split(" ")
        print(colored(column[0]+":"+column[1],'yellow'))
driver.quit()
print("")

os.system('clear')
os.system('cls')

#Proxy Connection

print(colored('Getting Proxies from graber...','green'))
time.sleep(2)
os.system('clear')
os.system('cls')
proxy = {"http": "http://"+ column[0]+":"+column[1]}
url = 'https://mobile.facebook.com/login'
r = requests.get(url,  proxies=proxy)
print("")
print(colored('Connecting using proxy' ,'green'))
print("")
sts = r.status_code

這是我在 python 中的基本類,用於請求模塊,帶有一些代理配置和秒表!

import requests
import time
class BaseCheck():
    def __init__(self, url):
        self.http_proxy  = "http://user:pw@proxy:8080"
        self.https_proxy = "http://user:pw@proxy:8080"
        self.ftp_proxy   = "http://user:pw@proxy:8080"
        self.proxyDict = {
                      "http"  : self.http_proxy,
                      "https" : self.https_proxy,
                      "ftp"   : self.ftp_proxy
                    }
        self.url = url
        def makearr(tsteps):
            global stemps
            global steps
            stemps = {}
            for step in tsteps:
                stemps[step] = { 'start': 0, 'end': 0 }
            steps = tsteps
        makearr(['init','check'])
        def starttime(typ = ""):
            for stemp in stemps:
                if typ == "":
                    stemps[stemp]['start'] = time.time()
                else:
                    stemps[stemp][typ] = time.time()
        starttime()
    def __str__(self):
        return str(self.url)
    def getrequests(self):
        g=requests.get(self.url,proxies=self.proxyDict)
        print g.status_code
        print g.content
        print self.url
        stemps['init']['end'] = time.time()
        #print stemps['init']['end'] - stemps['init']['start']
        x= stemps['init']['end'] - stemps['init']['start']
        print x


test=BaseCheck(url='http://google.com')
test.getrequests()

有點晚了,但這里有一個包裝類,它簡化了抓取代理,然后進行 http POST 或 GET:

代理請求

https://github.com/rootVIII/proxy_requests

如果你自己做,設置代理需要很多時間。 除此之外,開發人員采用的另一種方法是使用 API,這些 API 不僅可以自動設置代理,還可以處理速度、優化、可擴展性並確保安全可靠性。 使用python請求模塊設置代理的常用方法是運行命令“pip install proxy-requests”並按照官方文檔進行操作。 下面的代碼將幫助您獲得所需的結果。

源代碼:

import requests
proxies = {
 “http”: “http://10.10.10.10:8000”,
 “https”: “http://10.10.10.10:8000”,
}
r = requests.get(“http://toscrape.com”, proxies=proxies)

已經過測試,以下代碼有效。 需要使用 HTTPProxyAuth。

import requests
from requests.auth import HTTPProxyAuth


USE_PROXY = True
proxy_user = "aaa"
proxy_password = "bbb"
http_proxy = "http://your_proxy_server:8080"
https_proxy = "http://your_proxy_server:8080"
proxies = {
    "http": http_proxy,
    "https": https_proxy
}

def test(name):
    print(f'Hi, {name}')  # Press Ctrl+F8 to toggle the breakpoint.
    # Create the session and set the proxies.
    session = requests.Session()
    if USE_PROXY:
        session.trust_env = False
        session.proxies = proxies
        session.auth = HTTPProxyAuth(proxy_user, proxy_password)

    r = session.get('https://www.stackoverflow.com')
    print(r.status_code)

if __name__ == '__main__':
    test('aaa')

我分享了一些代碼,如何從站點“https://free-proxy-list.net”獲取代理並將數據存儲到與“Elite Proxy Switcher”(格式 IP:PORT)等工具兼容的文件中:

##PROXY_UPDATER - 從https://free-proxy-list.net/獲取免費代理

from lxml.html import fromstring
import requests
from itertools import cycle
import traceback
import re

######################FIND PROXIES#########################################
def get_proxies():
    url = 'https://free-proxy-list.net/'
    response = requests.get(url)
    parser = fromstring(response.text)
    proxies = set()
    for i in parser.xpath('//tbody/tr')[:299]:   #299 proxies max
        proxy = ":".join([i.xpath('.//td[1]/text()') 
        [0],i.xpath('.//td[2]/text()')[0]])
        proxies.add(proxy)
    return proxies



######################write to file in format   IP:PORT######################
try:
    proxies = get_proxies()
    f=open('proxy_list.txt','w')
    for proxy in proxies:
        f.write(proxy+'\n')
    f.close()
    print ("DONE")
except:
    print ("MAJOR ERROR")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM