首页 > 解决方案 > 无法停止 ThreadPoolExecutor

问题描述

我正在抓取数百个网址,每个网址都有我想要的数据排行榜,每个网址字符串之间的唯一区别是“平台”、“区域”,最后是页码。平台和地区只有几个,但页码每天都在变化,不知道有多少。这是第一个功能,我只是创建要并行请求的 url 列表。

如果我使用 page=1,那么结果将在最后一个函数中包含“table_rows > 0”。但是在 page=500 左右,请求的 url 仍然 ping 回来但很慢,然后它会显示错误消息,找不到排行榜,最后一个函数会显示 'table_rows == 0' 等。问题是我需要通过最后一页,我想快速执行此操作,因此使用 threadpoolexecutor - 但是一旦 PAGE_LIMIT 被触发,我就无法取消所有线程或进程或任何其他内容。我扔了 executor.shutdown(cancel_futures=True) 只是为了显示我在找什么。如果没有人可以帮助我,我将悲惨地删除并行化,我会慢慢地,可悲的是,一次一个 url...

谢谢

from concurrent.futures import ThreadPoolExecutor
from bs4 import BeautifulSoup 
import pandas
import requests

PLATFORM = ['xbl', 'psn', 'atvi', 'battlenet']
REGION = ['us', 'ca']
PAGE_LIMIT = True
def leaderboardLister():
    global REGION
    global PLATFORM
    list_url = []
    for region in REGION:
        for platform in PLATFORM:
            for i in range(1,750):
                list_url.append('https://cod.tracker.gg/warzone/leaderboards/battle-royale/' + platform + '/KdRatio?country=' + region + '&page=' + str(i))
                
            leaderboardExecutor(list_url,30)
            
def leaderboardExecutor(urls,threads):
    global PAGE_LIMIT
    global INTERNET
    if len(urls) > 0:                       
        with ThreadPoolExecutor(max_workers=threads) as executor:
            while True:
                if PAGE_LIMIT == False:
                    executor.shutdown(cancel_futures=True)

            while INTERNET == False:
                try:
                    print('bad internet')
                    requests.get("http://google.com")
                    INTERNET = True
                except:
                    time.sleep(3)
                    print('waited')
            
            executor.map(scrapeLeaderboardPage, urls)
    
    
def scrapeLeaderboardPage(url):
    global PAGE_LIMIT
    checkInternet()
    try:
        page = requests.get(url)
        soup = BeautifulSoup(page.content,features = 'lxml')
        table_rows = soup.find_all('tr')
        if len(table_rows) == 0:
            PAGE_LIMIT = False 
            print(url)
        else:
            pass
        print('success')
        

    except:
        INTERNET = False

leaderboardLister()

标签: pythonmultithreadingpython-requeststhreadpoolthreadpoolexecutor

解决方案


推荐阅读