219

Python用の優れたRequestsモジュールについての簡潔で単純なものです。

変数「プロキシ」に何が含まれるべきかをドキュメントで見つけることができないようです。標準の「IP:PORT」値を使用してdictを送信すると、2つの値を要求することを拒否しました。だから、私は(これはドキュメントでカバーされていないように見えるので)最初の値はIPであり、2番目はポートであると思いますか?

ドキュメントはこれだけに言及しています:

プロキシ–(オプション)プロキシのURLへの辞書マッピングプロトコル。

だから私はこれを試しました...私は何をすべきですか?

proxy = { ip: port}

そして、それらをdictに入れる前に、これらを何らかのタイプに変換する必要がありますか?

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

12 に答える 12

372

proxies'dict構文はです{"protocol":"ip:port", ...}これを使用すると、 httphttps、およびftpプロトコルを使用する要求に対して異なる(または同じ)プロキシを指定できます。

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

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

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

requestsドキュメントから推測:

パラメータ:
method –新しいRequestオブジェクトのメソッド。
url–新しいRequestオブジェクトのURL。
...
proxies–(オプション)プロキシのURLへの辞書マッピング プロトコル。 ..。


Linuxでは、、、HTTP_PROXYおよびHTTPS_PROXY環境FTP_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

これを指摘してくれたJayに感謝します。
構文はリクエスト2.0.0で変更されました。
URLにスキーマを追加する必要があります: https ://2.python-requests.org/en/latest/user/advanced/#proxies

于 2011-11-27T18:08:32.930 に答える
39

ここでプロキシのドキュメントを参照できます。

プロキシを使用する必要がある場合は、任意のリクエストメソッドのプロキシ引数を使用して個々のリクエストを設定できます。

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基本認証を使用するには、http:// user:password@host.com/構文を使用します。

proxies = {
    "http": "http://user:pass@10.10.1.10:3128/"
}
于 2012-11-15T10:13:52.913 に答える
36

urllibには、システムのプロキシ設定を取得するための非常に優れたコードがいくつかあり、それらはたまたま直接使用するための正しい形式になっていることがわかりました。あなたはこれを次のように使うことができます:

import urllib

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

それは本当にうまく機能し、urllibはMacOSXとWindowsの設定も取得することを知っています。

于 2013-05-01T01:54:46.973 に答える
21

受け入れられた答えは私にとって良いスタートでしたが、私は次のエラーを受け取り続けました:

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
            }

なぜオリジナルがうまくいくのか、私ではうまくいかないのか興味があります。

編集:これを反映するようにメインの回答が更新されたようです:)

于 2014-02-03T14:28:29.147 に答える
12

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/')
于 2018-11-30T18:16:19.033 に答える
7

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
于 2020-02-22T14:10:55.850 に答える
2

プロキシグラバーを作成したばかりで、ここに入力しなくても同じグラブプロキシに接続できます。

#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
于 2018-12-25T12:24:12.953 に答える
1

これが、いくつかのプロキシ構成とストップウォッチを備えたリクエストモジュール用の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()
于 2012-11-13T14:30:51.110 に答える
1

ドキュメント には、プロキシの使用法の非常に明確な例が示されています

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のプロキシを構成できるという事実です。これは、スクレイプしたいWebサイトごとに異なるプロキシを使用する場合に便利です。

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')
于 2022-02-17T07:11:26.103 に答える
0

少し遅れていますが、プロキシのスクレイピングとhttpPOSTまたはGETの作成を簡素化するラッパークラスを次に示します。

ProxyRequests

https://github.com/rootVIII/proxy_requests
于 2018-08-08T15:02:16.203 に答える
0

すでにテスト済みで、次のコードが機能します。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')
于 2021-11-24T19:09:44.697 に答える
-2

サイト「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")
于 2020-07-12T18:45:08.970 に答える