首页 > 解决方案 > 如何应用多线程从 1000 个 URL 列表中获取工作 URL - Python

问题描述

通常检查 1000 个 URL 的状态代码需要 9 小时 30 分钟我如何为这些 URL 应用多线程,我的输出应该是工作 URL,其状态代码为 200。例如,在 100 个 URL 中,我们有 70 个具有 200 个代码和剩下 404 或其他任何东西。

输入=[' https://xxxxxx1 ',' https ://xxxxxx2',........,'https ://xxxxxx100 ']

输出:- [' https://xxxxxx1 ',' https://xxxxxx2 ',' https ://xxxxxx3',........,'https ://xxxxxx70 ']这些会有200 状态码

标签: python-3.xweb-scrapingpython-requests

解决方案


只是一个关于线程在 python 中如何简单工作的建议。您可以使用将您的 url 列表一分为二,然后创建两个函数,它们在两个单独的线程上运行。

import threading 
Output = []
List1 = [half of your urls]
List2 = [other half of your urls]  
def check_status(lst): 
    """
    Do you task
    """

def check_status(lst): 
    """
    Do you task
    """

if __name__ == "__main__": 
    # creating thread 
    t1 = threading.Thread(target=check_status, args=(List1,)) 
    t2 = threading.Thread(target=check_status_2, args=(List2,)) 

    # starting thread 1 
    t1.start() 
    # starting thread 2 
    t2.start() 

    # wait until thread 1 is completely executed 
    t1.join() 
    # wait until thread 2 is completely executed 
    t2.join() 

    # both threads completely executed 
    print("Completed") 

一旦线程启动,您的程序也会继续执行。为了在线程完成之前停止执行正在进行的程序,请使用join方法。将给出 200 状态代码的 url 附加到输出


推荐阅读