【问题标题】:Fastest Proxy Iteration in PythonPython 中最快的代理迭代
【发布时间】:2020-07-15 16:11:39
【问题描述】:

假设我有一个包含 10,000 多个代理的列表

proxy_list = ['ip:port','ip:port',.....10,000+ items]

如何迭代它以获得适用于我的电脑的代理?使用以下代码可以找到它,但需要 5*10,000 秒才能完成。如何更快地遍历列表?

import requests
result=[]
for I in proxy_list:
    try:
        requests.get('http:\\www.httpbin.org\ip',proxies = {'https' : I, 'http' : I } ,timeout = 5)
        result.append(I)
    except:
        pass

【问题讨论】:

    标签: python python-3.x list python-requests iterator


    【解决方案1】:

    您可以使用线程,这将允许程序一次检查多个代理。

    import requests
    import threading
    import concurrent.futures
    
    appendLock = threading.Lock() """This is to keep multiple threads from appending 
    to the list at the same time"""
    
    workers = 10 """This is the number of threads that will iterate through your proxy list.
    In my experience, increasing this number higher than 30 causes problems."""
    
    proxy_list = ['ip:port','ip:port',.....10,000+ items]
    
    result = []
    
    def proxyCheck(proxy):
        try:
            requests.get('http://www.httpbin.org/ip',proxies = {'https' : I, 'http' : I } ,timeout = 5)
            with appendLock:
                result.append(I)
        except:
            pass
    
    with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as executor:
        for proxy in proxy_list:
            executor.submit(proxyCheck(proxy))
    

    【讨论】:

    • 那么如果我给worker=20,它会减少20的时间吗?脚本不会滞后吗?
    • 不,程序只是为自己分配更多来自 CPU 的处理能力。传统上,Python 程序将使用 1 个线程运行。但是在这种情况下,使用 concurrent.futures 可以让我们使用多个线程,从而有效地加快程序速度。在我脱离联盟之前,我无法深入了解细节,所以这里有一篇文章很好地解释了 Python 中的线程:realpython.com/intro-to-python-threading
    • 所以我可以使用线程运行两个循环,一个在后台(守护进程),一个以正常方式运行?谢谢。 +1 回答我的其他疑问之一
    • 还是一张一张的拍
    • 试过appendLock = threading.Lock() workers = 20 print("getting....") def proxyCheck(proxy,wow): try: res=requests.get('http://www.httpbin.org/ip',proxies = {'https' : proxy, 'http' : proxy } ,timeout = 4) print(res.json()) with appendLock: proxyman.append(wow) except: pass with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as executor: for i in result: proxy = i[0]+':'+i[1] executor.submit(proxyCheck(proxy,i))它会慢慢打印 1 by 1
    猜你喜欢
    • 2013-11-16
    • 2020-07-14
    • 1970-01-01
    • 2014-08-21
    • 2012-11-14
    • 2019-04-08
    • 2023-04-11
    • 1970-01-01
    • 2019-05-19
    相关资源
    最近更新 更多