在Python中,可以使用threading
庫來實現多線程爬蟲。為了實現任務取消和恢復,你可以使用threading.Event
對象。Event
對象可以用來在線程之間傳遞信號,例如取消或恢復任務。
以下是一個簡單的示例,展示了如何使用threading.Event
實現任務取消和恢復:
import threading
import requests
from bs4 import BeautifulSoup
class WebCrawler:
def __init__(self, urls, event):
self.urls = urls
self.event = event
self.threads = []
def crawl(self, url):
try:
response = requests.get(url)
if response.status_code == 200:
soup = BeautifulSoup(response.text, 'html.parser')
print(f"Crawled {url}")
else:
print(f"Failed to crawl {url}")
except Exception as e:
print(f"Error while crawling {url}: {e}")
def start(self):
for url in self.urls:
thread = threading.Thread(target=self.crawl, args=(url,))
thread.start()
self.threads.append(thread)
def cancel(self):
self.event.set()
def resume(self):
self.event.clear()
def join(self):
for thread in self.threads:
thread.join()
if __name__ == "__main__":
urls = [
"https://www.example.com",
"https://www.example2.com",
"https://www.example3.com"
]
event = threading.Event()
crawler = WebCrawler(urls, event)
# Start crawling
crawler.start()
# Wait for a while and cancel the task
import time
time.sleep(5)
crawler.cancel()
# Wait for all threads to finish
crawler.join()
在這個示例中,我們創建了一個名為WebCrawler
的類,它接受一個URL列表和一個Event
對象。crawl
方法用于爬取URL,start
方法用于啟動所有線程,cancel
方法用于設置事件以取消任務,resume
方法用于清除事件以恢復任務。join
方法用于等待所有線程完成。
要使用這個類,你需要創建一個WebCrawler
實例,傳入URL列表和一個Event
對象。然后,你可以調用start
方法啟動爬蟲,使用cancel
方法取消任務,以及使用resume
方法恢復任務。