How to transfer form data using Scrapy from the command line?

How can I pass the username and password from the command line? Thank!

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

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

    def after_login(self, response):
        # check login succeed before going on
        if "authentication failed" in response.body:
            self.log("Login failed", level=log.ERROR)
            return

        # continue scraping with authenticated session...
+3
source share
2 answers

You can do

scrapy crawl spidername -a username="john" -a password="secret"

and then

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

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

    def after_login(self, response):
        # check login succeed before going on
        if "authentication failed" in response.body:
            self.log("Login failed", level=log.ERROR)
            return

        # continue scraping with authenticated session...
+4
source

Open a terminal and make sure that screening is installed.

  • scrapy shell

  • from scrapy.http import FormRequest

  • request=FormRequest(url='http://www.example.com/users/login.php',formdata={'username': 'john','password':'secret',})

information:

  • Scrapy 1.0.0
+4
source

All Articles