如果我们具有使用python scrapy的凭据,如何刮擦已登录的网页?

时间:2018-09-03 09:14:53

标签: python-2.7 scrapy-spider

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

1 个答案:

答案 0 :(得分:1)

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

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...