我的问题是:我想从某些域中提取所有有价值的文本,例如www.example.com。所以我访问这个网站并访问最大深度为2的所有链接并将其写入csv文件。
我在scrapy中编写了模块,它使用1个进程解决了这个问题,并产生了多个爬虫,但效率很低 - 我能够抓取~1k域/ ~5k个网站/ h,据我所知,我的瓶颈是CPU(因为GIL?)。离开我的电脑一段时间后,我发现我的网络连接断了。
当我想使用多个进程时,我只是从扭曲中得到错误:Multiprocessing of Scrapy Spiders in Parallel Processes所以这意味着我必须学习扭曲,我会说我弃用了,与asyncio相比,但这只是我的意见。 / p>
所以我有很多想法要做什么
您推荐什么解决方案?
Edit1:分享代码
class ESIndexingPipeline(object):
def __init__(self):
# self.text = set()
self.extracted_type = []
self.text = OrderedSet()
import html2text
self.h = html2text.HTML2Text()
self.h.ignore_links = True
self.h.images_to_alt = True
def process_item(self, item, spider):
body = item['body']
body = self.h.handle(str(body, 'utf8')).split('\n')
first_line = True
for piece in body:
piece = piece.strip(' \n\t\r')
if len(piece) == 0:
first_line = True
else:
e = ''
if not self.text.empty() and not first_line and not regex.match(piece):
e = self.text.pop() + ' '
e += piece
self.text.add(e)
first_line = False
return item
def open_spider(self, spider):
self.target_id = spider.target_id
self.queue = spider.queue
def close_spider(self, spider):
self.text = [e for e in self.text if comprehension_helper(langdetect.detect, e) == 'en']
if spider.write_to_file:
self._write_to_file(spider)
def _write_to_file(self, spider):
concat = "\n".join(self.text)
self.queue.put([self.target_id, concat])
电话:
def execute_crawler_process(targets, write_to_file=True, settings=None, parallel=800, queue=None):
if settings is None:
settings = DEFAULT_SPIDER_SETTINGS
# causes that runners work sequentially
@defer.inlineCallbacks
def crawl(runner):
n_crawlers_batch = 0
done = 0
n = float(len(targets))
for url in targets:
#print("target: ", url)
n_crawlers_batch += 1
r = runner.crawl(
TextExtractionSpider,
url=url,
target_id=url,
write_to_file=write_to_file,
queue=queue)
if n_crawlers_batch == parallel:
print('joining')
n_crawlers_batch = 0
d = runner.join()
# todo: print before yield
done += n_crawlers_batch
yield d # download rest of data
if n_crawlers_batch < parallel:
d = runner.join()
done += n_crawlers_batch
yield d
reactor.stop()
def f():
runner = CrawlerProcess(settings)
crawl(runner)
reactor.run()
p = Process(target=f)
p.start()
蜘蛛不是特别有趣。
答案 0 :(得分:3)
您可以使用Scrapy-Redis。它基本上是一个Scrapy蜘蛛,它从Redis中的队列中获取要爬网的URL。 优点是您可以启动许多并发蜘蛛,以便您可以更快地爬行。蜘蛛的所有实例都会从队列中提取URL,并在用完要爬网的URL时等待空闲。 Scrapy-Redis的存储库附带了一个实现它的示例项目。
我使用Scrapy-Redis启动64个爬虫实例,在大约1小时内抓取100万个URL。