使用 Python 'Requests' 模块的代理

2024-12-16 08:35:00
admin
原创
4517
摘要:问题描述:这只是关于Python 优秀的Requests模块的简短介绍。我在文档中似乎找不到变量“proxies”应该包含什么。当我向它发送一个带有标准“IP:PORT”值的字典时,它拒绝了并要求输入 2 个值。所以,我猜(因为文档中似乎没有涵盖这一点)第一个值是 ip,第二个值是端口?文档仅提到这一点:pr...

问题描述:

这只是关于Python 优秀的Requests模块的简短介绍。

我在文档中似乎找不到变量“proxies”应该包含什么。当我向它发送一个带有标准“IP:PORT”值的字典时,它拒绝了并要求输入 2 个值。所以,我猜(因为文档中似乎没有涵盖这一点)第一个值是 ip,第二个值是端口?

文档仅提到这一点:

proxies – (可选)将协议映射到代理的 URL 的字典。

所以我尝试了这个...我应该做什么?

proxy = { ip: port}

在将它们放入字典之前,我应该将它们转换为某种类型吗?

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

解决方案 1:

' 字典语法proxies是。使用它,你可以为使用httphttpsftp{"protocol": "scheme://ip:port", ...}协议的请求指定不同的(或相同的)代理:

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 – 新 Request 对象的方法。 –

urlRequest 对象的 URL。... – (可选)将协议

映射代理的 URL 的字典。...

proxies


在 Linux 上,您还可以通过、和环境变量执行HTTP_PROXYHTTPS_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

解决方案 2:

您可以在此处参考代理文档。

如果您需要使用代理,则可以使用任何请求方法的代理参数配置单独的请求:

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/"
}

解决方案 3:

我发现 urllib 有一些非常好的代码来获取系统的代理设置,而且它们恰好是可以直接使用的正确形式。你可以像这样使用:

import urllib

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

它运行得非常好,并且 urllib 也知道如何获取 Mac OS X 和 Windows 设置。

解决方案 4:

接受的答案对我来说是一个好的开始,但我一直收到以下错误:

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
            }

我很感兴趣为什么原版对某些人有用,但对我却没用。

编辑:我看到主要答案现已更新以反映这一点:)

解决方案 5:

如果您想要保留 cookies 和会话数据,最好这样做:

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/')

解决方案 6:

晚了 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

解决方案 7:

该文档
给出了代理使用的非常清晰的示例

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')

解决方案 8:

我刚刚制作了一个代理抓取器,并且可以无需任何输入连接相同的抓取代理,如下所示:

#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

解决方案 9:

这是我在 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()

解决方案 10:

已测试,以下代码有效。需要使用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')

解决方案 11:

有点晚了,但这里有一个包装类,可以简化抓取代理,然后进行 http POST 或 GET:

代理请求

https://github.com/rootVIII/proxy_requests

解决方案 12:

我分享了一些代码,关于如何从网站“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+'
')
    f.close()
    print ("DONE")
except:
    print ("MAJOR ERROR")
相关推荐
  政府信创国产化的10大政策解读一、信创国产化的背景与意义信创国产化,即信息技术应用创新国产化,是当前中国信息技术领域的一个重要发展方向。其核心在于通过自主研发和创新,实现信息技术应用的自主可控,减少对外部技术的依赖,并规避潜在的技术制裁和风险。随着全球信息技术竞争的加剧,以及某些国家对中国在科技领域的打压,信创国产化显...
工程项目管理   2482  
  为什么项目管理通常仍然耗时且低效?您是否还在反复更新电子表格、淹没在便利贴中并参加每周更新会议?这确实是耗费时间和精力。借助软件工具的帮助,您可以一目了然地全面了解您的项目。如今,国内外有足够多优秀的项目管理软件可以帮助您掌控每个项目。什么是项目管理软件?项目管理软件是广泛行业用于项目规划、资源分配和调度的软件。它使项...
项目管理软件   1533  
  PLM(产品生命周期管理)项目对于企业优化产品研发流程、提升产品质量以及增强市场竞争力具有至关重要的意义。然而,在项目推进过程中,范围蔓延是一个常见且棘手的问题,它可能导致项目进度延迟、成本超支以及质量下降等一系列不良后果。因此,有效避免PLM项目范围蔓延成为项目成功的关键因素之一。以下将详细阐述三大管控策略,助力企业...
plm系统   0  
  PLM(产品生命周期管理)项目管理在企业产品研发与管理过程中扮演着至关重要的角色。随着市场竞争的加剧和产品复杂度的提升,PLM项目面临着诸多风险。准确量化风险优先级并采取有效措施应对,是确保项目成功的关键。五维评估矩阵作为一种有效的风险评估工具,能帮助项目管理者全面、系统地评估风险,为决策提供有力支持。五维评估矩阵概述...
免费plm软件   0  
  引言PLM(产品生命周期管理)开发流程对于企业产品的全生命周期管控至关重要。它涵盖了从产品概念设计到退役的各个阶段,直接影响着产品质量、开发周期以及企业的市场竞争力。在当今快速发展的科技环境下,客户对产品质量的要求日益提高,市场竞争也愈发激烈,这就使得优化PLM开发流程成为企业的必然选择。缺陷管理工具和六西格玛方法作为...
plm产品全生命周期管理   0  
热门文章
项目管理软件有哪些?
曾咪二维码

扫码咨询,免费领取项目管理大礼包!

云禅道AD
禅道项目管理软件

云端的项目管理软件

尊享禅道项目软件收费版功能

无需维护,随时随地协同办公

内置subversion和git源码管理

每天备份,随时转为私有部署

免费试用