为什么我无法连接到代理?

Why can't I connect with a proxy?

我写了一个检查代理的小脚本:

async def proxy_check(session, proxy):
    global good_proxies
    proxy_str = f'http://{proxy}'
    async with semaphore:
        try:
            async with session.get(host, proxy=proxy_str, timeout=10) as r:
                if r.status == 200:
                    resp = await r.json()
                    if resp['ip'] == proxy:
                        good_proxies.append(proxy)
                        proxies.remove(proxy)
        except Exception:
            logging.exception(proxy)
            proxies.remove(proxy)


async def main():
    async with aiohttp.ClientSession() as session:
        tasks = []
        for proxy in proxies:
            tasks.append(asyncio.create_task(proxy_check(session, proxy)))
        await asyncio.gather(*tasks)  

但是当我 运行 它时,我得到了这些错误之一:

aiohttp.http_exceptions.BadHttpMessage: 400, message='invalid constant string' aiohttp.client_exceptions.ClientResponseError: 400, message='invalid constant string' concurrent.futures._base.TimeoutError

我的列表中有将近 20,000 个代理,而此脚本无法通过所有这些代理进行连接。没有一个代理在此脚本中不起作用。

但是如果你这样做:

proxy = {'http': f'http://{proxy}'}
r = requests.get(url, proxies=proxy)

一切正常。许多代理工作。 我做错了什么?

collection proxies 在您的 main 方法中迭代。它是由多个任务并行处理的元素。到目前为止这很好,但在处理功能中,您正在更改您正在处理的 collection。这会导致 race condition 导致 损坏您正在迭代的 collection

  1. 你永远不应该改变你正在接受的 collection。
  2. 如果您有代码并行更改共享资源,则需要使用 mutual exclusion to make it thread-safe. You could use "Lock" in python 3.7.