Python请求代理错误'无法解析'

问题描述 投票:1回答:3

我正在尝试使用代理列表来抓取页面。这个小问题让我疯狂。当我像这样直接输入代理时它可以工作:

proxies = {
            'http': 'http://10.0.1.1:8080',
            'https': 'http://10.0.1.1:8080'
        }

但是,当我使用类似的东西

http_proxy =  'http://'+proxy
https_proxy = 'https://'+proxy



    proxies = {
            'http': http_proxy,
            'https': https_proxy,
        }

requests.packages.urllib3.exceptions.LocationParseError:无法解析:10.0.1.1:8080

我收到这个错误。这绝对没有意义。

编辑:我刚刚意识到它可能是因为每个代理后的换行符我在服务器上托管了proxylist.txt所以现在我需要找出如何在每个代理之后摆脱换行,我尝试了像proxy.strip这样的东西(' \ n')但这也不起作用

python python-requests
3个回答
1
投票

使用后,总是检查.split可能有额外的字符我修复了我的项目使用

splitlines()

1
投票

我尝试了2行的proxylist.txt 10.0.1.1:8080 10.0.1.1:8181

并在代码下执行,

with open('proxylist.txt','r') as reader :
    for line in reader :
        proxy = line.split('\n', 1)[0]
        http_proxy =  'http://'+proxy
        https_proxy = 'https://'+proxy

        proxies = {
            'http': http_proxy,
            'https': https_proxy,
        }

        print proxies

得到预期的输出, {'http':'http://10.0.1.1:8080','https':'https://10.0.1.1:8080'} {'http':'http://10.0.1.1:8181','https':'https://10.0.1.1:8181'}


0
投票

因为那个问题我疯了。

尝试这样做:

def chomp(x):
    if x.endswith("\r\n"):
        return x[:-2]
    if x.endswith("\n") or x.endswith("\r"):
        return x[:-1]
    return x

    http_proxy =  'http://' + chomp(proxy)
    https_proxy = 'https://' + chomp(proxy)

    proxies = {
            'http': http_proxy,
            'https': https_proxy,
        }

它帮助解决了我的问题。

© www.soinside.com 2019 - 2024. All rights reserved.