我正在使用最新版本的 scrapy ( http://doc.scrapy.org/en/latest/index.html ),并试图弄清楚如何使 scrapy 仅抓取作为其一部分的 URL start_url 列表。在大多数情况下,我只想抓取 1 个页面,但在某些情况下,我可能会指定多个页面。我不希望它爬行到其他页面。
我尝试设置深度级别=1,但我不确定在测试中它是否达到了我希望达到的目标。
任何帮助将不胜感激!
谢谢你!
2015-12-22 - 代码更新:
# -*- coding: utf-8 -*-
import scrapy
from generic.items import GenericItem
class GenericspiderSpider(scrapy.Spider):
name = "genericspider"
def __init__(self, domain, start_url, entity_id):
self.allowed_domains = [domain]
self.start_urls = [start_url]
self.entity_id = entity_id
def parse(self, response):
for href in response.css("a::attr('href')"):
url = response.urljoin(href.extract())
yield scrapy.Request(url, callback=self.parse_dir_contents)
def parse_dir_contents(self, response):
for sel in response.xpath("//body//a"):
item = GenericItem()
item['entity_id'] = self.entity_id
# gets the actual email address
item['emails'] = response.xpath("//a[starts-with(@href, 'mailto')]").re(r'mailto:\s*(.*?)"')
yield item
Run Code Online (Sandbox Code Playgroud)
下面,在第一个响应中,您提到使用通用蜘蛛——这不是我在代码中所做的吗?您还建议我删除
callback=self.parse_dir_contents
Run Code Online (Sandbox Code Playgroud)
来自解析函数?
谢谢。
看起来您正在使用CrawlSpider一种特殊的方式Spider来抓取页面内的多个类别。
如果只抓取内部指定的 url ,start_urls只需重写该parse方法,因为这是启动请求的默认回调。