我正在使用scrapy的CrawlSpider
蜘蛛类迭代start_urls
列表并抓取每个站点的内部页面以获取电子邮件地址。我想为每个start_url导出一个带有单个(唯一)项的文件,以及匹配的电子邮件列表。为此,我需要覆盖make_requests_from_url
和parse
方法,以便我可以将响应的元数据中的每个start_url项(请参阅代码)传递给内部页面。运行此代码的输出是:
www.a.com,['webmaster@a.com']
www.a.com,['webmaster@a.com','info@a.com']
www.a.com,['webmaster@a.com','info@a.com','admin@a.com']
但是,我只希望导出文件包含上述输出中的最后一个条目
(www.a.com,['admin@a.com,webmaster@a.com, info@a.com'])
这可能吗?
代码:
class MySpider(CrawlSpider):
start_urls = [... urls list ...]
def parse(self, response):
for request_or_item in CrawlSpider.parse(self, response):
if isinstance(request_or_item, Request):
request_or_item.meta.update(dict(url_item=response.meta['url_item']))
yield request_or_item
def make_requests_from_url(self, url):
# Create a unique item for each url. Append email to this item from internal pages
url_item = MyItem()
url_item["url"] = url
url_item["emais"] = []
return Request(url, dont_filter=True, meta = {'url_item': url_item})
def parse_page(self, response):
url_item = response.meta["url_item"]
url_item["emails"].append(** some regex of emails from the response object **)
return url_item