Scrapy 可以通过使用多线程或多进程来提高爬取效率。以下是一些实现方式:
import threading
def start_crawl(url):
process = CrawlerProcess(get_project_settings())
process.crawl(MySpider, start_urls=[url])
process.start()
urls = ['http://example.com/page1', 'http://example.com/page2', 'http://example.com/page3']
threads = []
for url in urls:
thread = threading.Thread(target=start_crawl, args=(url,))
thread.start()
threads.append(thread)
for thread in threads:
thread.join()
import multiprocessing
def start_crawl(url):
process = CrawlerProcess(get_project_settings())
process.crawl(MySpider, start_urls=[url])
process.start()
urls = ['http://example.com/page1', 'http://example.com/page2', 'http://example.com/page3']
processes = []
for url in urls:
process = multiprocessing.Process(target=start_crawl, args=(url,))
process.start()
processes.append(process)
for process in processes:
process.join()
需要注意的是,多线程和多进程爬取都会增加系统资源消耗,尤其是内存和 CPU 使用率。因此,需要根据实际情况选择合适的方式来提高爬取效率。