所以我有這樣的代碼:
站點串列
a.com
b.com
c.com
d.com
e.com
etc
代理名單
1.1.1.1
2.2.2.2
etc
def extract(url, proxy):
print(f'Thread Name : {threading.current_thread().name}')
print(f'We are using this proxy : {proxy}')
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:80.0) Gecko/20100101 Firefox/80.0'}
try:
r = requests.get(url, headers=headers, proxies={'http' : proxy,'https': proxy}, timeout=2)
soup = BeautifulSoup(r.text, 'html.parser')
page_title = soup.find('title').text.strip()
print(page_title)
except:
pass
我需要回圈提取函式,直到串列中的所有站點都完成為止。根據我所知道的concurent.futurespython 中的內容,我在這里嘗試:
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
executor.map(extract, url_list, proxy_list)
問題是,假設我只有 2 個有效代理,并且我有 5 個站點,代碼將僅在 2 個代理中停止,
如何解決這個問題呢 ?所以我想要的是每個執行緒都有自己的代理,并完成任務,直到串列中的所有站點完成..
謝謝
uj5u.com熱心網友回復:
使用itertools.cycle創建一個無限重復代理的迭代器
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
executor.map(extract, url_list, itertools.cycle(proxy_list))
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/337172.html
