Попытка входа с помощью scrapy

Я пытаюсь войти с помощью scrapy. Тем не менее, получение одной и той же ошибки снова и снова.Не уверен, что я делаю правильно. Вот мой код:

 #!/usr/bin/python
# -*- coding:utf-8-*-
import scrapy
class LoginSpider(scrapy.Spider):
    name = 'lostfilm.tv'
    start_urls = ['http://www.lostfilm.tv/login',]
    def parse(self, response):
        return scrapy.FormRequest.from_response(
            response,
            formname = 'login',
            formdata = {('Логин / E-Mail:').decode('utf-8') : ('myemail@yahoo.com').decode('utf-8')},
            callback=self.after_login
        )
    def log_password(self, response):
         return scrapy.FormRequest.from_response(
             response,
             formname = 'password',
             formdata = {('Пароль:').decode('utf-8'): ('pass').decode('utf-8')},
             callback=self.after_login
        )
def after_login(self, response):
   if "Username" in response.body:
       self.logger.warning("Success")
       return

Выход:

    user@debian:~/Python/wrk/lostfilm.tv/lostfilm$ scrapy crawl lostfilm.tv
2017-01-16 15:37:19 [scrapy.utils.log] INFO: Scrapy 1.3.0 started (bot: lostfilm)
2017-01-16 15:37:19 [scrapy.utils.log] INFO: Overridden settings: {'NEWSPIDER_MODULE': 'lostfilm.spiders', 'SPIDER_MODULES': ['lostfilm.spiders'], 'ROBOTSTXT_OBEY': True, 'BOT_NAME': 'lostfilm'}
2017-01-16 15:37:19 [scrapy.middleware] INFO: Enabled extensions:
['scrapy.extensions.logstats.LogStats',
 'scrapy.extensions.telnet.TelnetConsole',
 'scrapy.extensions.corestats.CoreStats']
2017-01-16 15:37:19 [scrapy.middleware] INFO: Enabled downloader middlewares:
['scrapy.downloadermiddlewares.robotstxt.RobotsTxtMiddleware',
 'scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware',
 'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware',
 'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware',
 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware',
 'scrapy.downloadermiddlewares.retry.RetryMiddleware',
 'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware',
 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware',
 'scrapy.downloadermiddlewares.redirect.RedirectMiddleware',
 'scrapy.downloadermiddlewares.cookies.CookiesMiddleware',
 'scrapy.downloadermiddlewares.stats.DownloaderStats']
2017-01-16 15:37:19 [scrapy.middleware] INFO: Enabled spider middlewares:
['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware',
 'scrapy.spidermiddlewares.offsite.OffsiteMiddleware',
 'scrapy.spidermiddlewares.referer.RefererMiddleware',
 'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware',
 'scrapy.spidermiddlewares.depth.DepthMiddleware']
2017-01-16 15:37:19 [scrapy.middleware] INFO: Enabled item pipelines:
[]
2017-01-16 15:37:19 [scrapy.core.engine] INFO: Spider opened
2017-01-16 15:37:19 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2017-01-16 15:37:19 [scrapy.extensions.telnet] DEBUG: Telnet console listening on 127.0.0.1:6023
2017-01-16 15:37:19 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://www.lostfilm.tv/robots.txt> (referer: None)
2017-01-16 15:37:20 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://www.lostfilm.tv/login> (referer: None)
2017-01-16 15:37:20 [scrapy.core.scraper] ERROR: Spider error processing <GET http://www.lostfilm.tv/login> (referer: None)
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/twisted/internet/defer.py", line 651, in _runCallbacks
    current.result = callback(current.result, *args, **kw)
  File "/home/user/Python/wrk/lostfilm.tv/lostfilm/lostfilm/spiders/lostfilm.py", line 13, in parse
    callback=self.after_login
AttributeError: 'LoginSpider' object has no attribute 'after_login'
2017-01-16 15:37:20 [scrapy.core.engine] INFO: Closing spider (finished)
2017-01-16 15:37:20 [scrapy.statscollectors] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 441,
 'downloader/request_count': 2,
 'downloader/request_method_count/GET': 2,
 'downloader/response_bytes': 20775,
 'downloader/response_count': 2,
 'downloader/response_status_count/200': 2,
 'finish_reason': 'finished',
 'finish_time': datetime.datetime(2017, 1, 16, 20, 37, 20, 408406),
 'log_count/DEBUG': 3,
 'log_count/ERROR': 1,
 'log_count/INFO': 7,
 'response_received_count': 2,
 'scheduler/dequeued': 1,
 'scheduler/dequeued/memory': 1,
 'scheduler/enqueued': 1,
 'scheduler/enqueued/memory': 1,
 'spider_exceptions/AttributeError': 1,
 'start_time': datetime.datetime(2017, 1, 16, 20, 37, 19, 369971)}
2017-01-16 15:37:20 [scrapy.core.engine] INFO: Spider closed (finished)

Мало вопросов:

  1. В моем случае обе формы имеют значение formname. Можно ли войти в систему без formdata?
    2.Если я использую formdata, должен ли я передавать фактические метки входа? Это означает, что версии ru вместо {‘password’: ‘myrealpass’}.
    Спасибо!

1 ответ

  1. Вы получаете ошибку, чтоLoginSpider has no attribute after_login, потому что вы не отступ after_loginметода:

    class LoginSpider(scrapy.Spider):
        name = 'lostfilm.tv'
        start_urls = ['http://www.lostfilm.tv/login',]
    
        ...
    
        def after_login(self, response):
           if "Username" in response.body:
               self.logger.warning("Success")
               return