[英]Python multithreading web crawling
我有一個簡單的Web搜尋器 ,每秒可爬行約4個(特定)網站。 如果我在兩個不同的Python IDE中運行腳本,則可以使速度加倍,因為這兩個程序都以每秒〜4的速度運行代碼。 為什么我的代碼運行得比預期的慢? 還是因為我使用一種愚蠢的方法通過同時使用兩個不同的IDE使我的腳本使用多線程/多處理而更快?
我使用的是Python 3.5.2。
對於工作線程池來說,這聽起來像是一項艱巨的任務。
請參閱: Python:多處理模塊
如注釋中所述,所有這些都與線程有關。
現在為您的程序提供了一個解決方案:
import requests
import threading
class Crawler:
def __init__(self, url):
self.url = url
self.session = requests.Session()
def crawl(self):
page = self.session.get(url)
# Do your crawling here
with open('urls.txt', 'r') as f: # Assuming you use a file with a list of URLs
for url in f:
while(threading.active_count() > 20): # Use 20 threads
time.sleep(0.1)
c = Crawler(url)
t = threading.Thread(target = c.crawl())
請注意threading.active_count()
也計入主線程。
而且,您應該在HTTP請求中使用超時。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.