使用带有scrapy的loginform

时间:2015-04-22 21:49:43

标签: python authentication scrapy

scrapy框架(https://github.com/scrapy/scrapy)提供了一个库,供登录需要身份验证的网站https://github.com/scrapy/loginform时使用。 我查看了两个程序的文档但是我似乎无法弄清楚如何让scrapy在运行之前调用loginform。只需登录表单,登录工作正常 感谢

1 个答案:

答案 0 :(得分:15)

loginform只是一个图书馆,完全与Scrapy脱钩。

您必须编写代码以将其插入所需的蜘蛛中,可能采用回调方法。

以下是执行此操作的结构示例:

import scrapy
from loginform import fill_login_form

class MySpiderWithLogin(scrapy.Spider):
    name = 'my-spider'

    start_urls = [
        'http://somewebsite.com/some-login-protected-page',
        'http://somewebsite.com/another-protected-page',
    ]

    login_url = 'http://somewebsite.com/login-page'

    login_user = 'your-username'
    login_password = 'secret-password-here'

    def start_requests(self):
        # let's start by sending a first request to login page
        yield scrapy.Request(self.login_url, self.parse_login)

    def parse_login(self, response):
        # got the login page, let's fill the login form...
        data, url, method = fill_login_form(response.url, response.body,
                                            self.login_user, self.login_password)

        # ... and send a request with our login data
        return scrapy.FormRequest(url, formdata=dict(data),
                           method=method, callback=self.start_crawl)

    def start_crawl(self, response):
        # OK, we're in, let's start crawling the protected pages
        for url in self.start_urls:
            yield scrapy.Request(url)

    def parse(self, response):
        # do stuff with the logged in response