首页 > 解决方案 > 如果我们有使用 python scrapy 的凭据,如何抓取已登录的网页?

问题描述

只想知道如何将请求与登录凭据一起发送到登录页面以获取数据。

标签: python-2.7scrapy-spider

解决方案


网站通常通过元素提供预填充的表单字段,例如会话相关数据或身份验证令牌(用于登录页面)。抓取时,您会希望自动预填充这些字段,并且只覆盖其中的几个,例如用户名和密码。您可以为此作业使用 FormRequest.from_response() 方法。这是一个使用它的示例蜘蛛:import scrapy

def authentication_failed(response):
    # TODO: Check the contents of the response and return True if it failed
    # or False if it succeeded.
    pass

class LoginSpider(scrapy.Spider):
    name = 'example.com'
    start_urls = ['http://www.example.com/users/login.php']

    def parse(self, response):
        return scrapy.FormRequest.from_response(
            response,
            formdata={'username': 'john', 'password': 'secret'},
            callback=self.after_login
        )

    def after_login(self, response):
        if authentication_failed(response):
            self.logger.error("Login failed")
            return

        # continue scraping with authenticated session...

推荐阅读