33

在我之前的问题中,我对我的问题不是很具体(使用 Scrapy 的经过身份验证的会话进行抓取),希望能够从更一般的答案中推断出解决方案。我可能宁愿使用这个词crawling

所以,到目前为止,这是我的代码:

class MySpider(CrawlSpider):
    name = 'myspider'
    allowed_domains = ['domain.com']
    start_urls = ['http://www.domain.com/login/']

    rules = (
        Rule(SgmlLinkExtractor(allow=r'-\w+.html$'), callback='parse_item', follow=True),
    )

    def parse(self, response):
        hxs = HtmlXPathSelector(response)
        if not "Hi Herman" in response.body:
            return self.login(response)
        else:
            return self.parse_item(response)

    def login(self, response):
        return [FormRequest.from_response(response,
                    formdata={'name': 'herman', 'password': 'password'},
                    callback=self.parse)]


    def parse_item(self, response):
        i['url'] = response.url

        # ... do more things

        return i

如您所见,我访问的第一个页面是登录页面。如果我还没有通过身份验证(在parse函数中),我会调用我的自定义login函数,该函数会发布到登录表单。然后,如果我通过了身份验证,我想继续爬取。

问题是parse我试图覆盖以登录的功能,现在不再进行必要的调用来抓取任何其他页面(我假设)。而且我不确定如何保存我创建的项目。

以前有人做过这样的事情吗?(验证,然后爬行,使用 a CrawlSpider)任何帮助将不胜感激。

4

4 回答 4

57

不要覆盖 a 中的parse函数CrawlSpider

当你使用 aCrawlSpider时,你不应该重写这个parse函数。这里的CrawlSpider文档中有一个警告:http: //doc.scrapy.org/en/0.14/topics/spiders.html#scrapy.contrib.spiders.Rule

这是因为使用CrawlSpider, parse(任何请求的默认回调)发送要由Rules 处理的响应。


爬取前登录:

为了在蜘蛛开始爬行之前进行某种初始化,您可以使用 an InitSpider(继承自 a CrawlSpider)并覆盖该init_request函数。该函数将在蜘蛛初始化时和开始爬行之前调用。

为了让 Spider 开始爬行,您需要调用self.initialized.

您可以在此处阅读负责此操作的代码(它有有用的文档字符串)。


一个例子:

from scrapy.contrib.spiders.init import InitSpider
from scrapy.http import Request, FormRequest
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.contrib.spiders import Rule

class MySpider(InitSpider):
    name = 'myspider'
    allowed_domains = ['example.com']
    login_page = 'http://www.example.com/login'
    start_urls = ['http://www.example.com/useful_page/',
                  'http://www.example.com/another_useful_page/']

    rules = (
        Rule(SgmlLinkExtractor(allow=r'-\w+.html$'),
             callback='parse_item', follow=True),
    )

    def init_request(self):
        """This function is called before crawling starts."""
        return Request(url=self.login_page, callback=self.login)

    def login(self, response):
        """Generate a login request."""
        return FormRequest.from_response(response,
                    formdata={'name': 'herman', 'password': 'password'},
                    callback=self.check_login_response)

    def check_login_response(self, response):
        """Check the response returned by a login request to see if we are
        successfully logged in.
        """
        if "Hi Herman" in response.body:
            self.log("Successfully logged in. Let's start crawling!")
            # Now the crawling can begin..
            return self.initialized()
        else:
            self.log("Bad times :(")
            # Something went wrong, we couldn't log in, so nothing happens.

    def parse_item(self, response):

        # Scrape data from page

保存项目:

您的 Spider 返回的项目被传递到管道,该管道负责对数据执行您想要执行的任何操作。我建议您阅读文档:http ://doc.scrapy.org/en/0.14/topics/item-pipeline.html

如果您对Items 有任何问题/疑问,请随时提出新问题,我会尽力提供帮助。

于 2011-05-02T12:37:36.843 回答
4

为了使上述解决方案起作用,我必须通过在 scrapy 源代码上更改以下内容来使 CrawlSpider 从 InitSpider 继承,而不是从 BaseSpider 继承。在文件 scrapy/contrib/spiders/crawl.py 中:

  1. 添加:from scrapy.contrib.spiders.init import InitSpider
  2. 更改class CrawlSpider(BaseSpider)class CrawlSpider(InitSpider)

否则蜘蛛不会调用该init_request方法。

还有其他更简单的方法吗?

于 2012-01-05T20:41:33.440 回答
2

如果您需要的是Http 身份验证,请使用提供的中间件挂钩。

settings.py

DOWNLOADER_MIDDLEWARE = [ 'scrapy.contrib.downloadermiddleware.httpauth.HttpAuthMiddleware']

并在您的spider class添加属性中

http_user = "user"
http_pass = "pass"
于 2011-07-26T06:31:45.010 回答
2

Just adding to Acorn's answer above. Using his method my script was not parsing the start_urls after the login. It was exiting after a successful login in check_login_response. I could see I had the generator though. I needed to to use

return self.initialized()

then the parse function was called.

于 2014-07-15T04:37:15.110 回答