在Scrapy中使用经过身份验证的会话进行爬网

时间:2011-05-01 20:34:33

标签: python scrapy

在我的previous question中,我对我的问题不太具体(使用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函数以便登录,现在不再进行必要的调用来刮掉任何其他页面(我假设)。而且我不确定如何保存我创建的项目。

之前有人做过这样的事吗? (使用CrawlSpider进行身份验证,然后抓取)任何帮助都将不胜感激。

4 个答案:

答案 0 :(得分:54)

请勿覆盖parse中的CrawlSpider功能:

当您使用CrawlSpider时,不应覆盖parse功能。这里的CrawlSpider文档中有一条警告:http://doc.scrapy.org/en/0.14/topics/spiders.html#scrapy.contrib.spiders.Rule

这是因为使用CrawlSpiderparse(任何请求的默认回调)会发送响应以由Rule处理。


在抓取之前登录:

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

为了让Spider开始抓取,您需要致电self.initialized

您可以阅读对此here负责的代码(它有帮助的文档字符串)。


示例:

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返回的项目将传递给Pipeline,后者负责对数据执行任何操作。我建议您阅读文档:http://doc.scrapy.org/en/0.14/topics/item-pipeline.html

如果您对Item有任何问题/疑问,请不要犹豫,提出新问题,我会尽力帮助您。

答案 1 :(得分:2)

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

settings.py

中的

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

并在spider class添加属性

http_user = "user"
http_pass = "pass"

答案 2 :(得分:2)

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

  1. 添加:from scrapy.contrib.spiders.init import InitSpider
  2. class CrawlSpider(BaseSpider)更改为class CrawlSpider(InitSpider)
  3. 否则蜘蛛不会调用init_request方法。

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

答案 3 :(得分:2)

刚刚添加到Acorn的答案上面。 使用他的方法我的脚本在登录后没有解析start_urls。 在check_login_response成功登录后退出。 我可以看到我有发电机。 我需要使用

return self.initialized()

然后调用了解析函数。

相关问题