Scrapy Spider登录问题

时间:2018-11-07 19:33:11

标签: web-scraping scrapy

您好,我正在尝试通过scrapy登录网站。我有点困惑,因为首先,如果我搜索令牌,则登录页面上有两个__RequestVerificationTokens。其次,当我检查页面以成功登录后找到302重定向时,我找不到该重定向。

当前,如果我运行我的代码而不管我的用户名和密码正确无误,那么我将得到相同的结果。如果我将随机字符串作为令牌传递,则会刮出错误并重定向到页面未找到错误。

我需要做什么才能获得身份验证并重定向到主页,就像我自己登录一样?

# -*- coding: utf-8 -*-
import scrapy
from scrapy.http import FormRequest

class LoginSpider(scrapy.Spider):
    name = "login"
    allowed_domains = ["albertacannabis.org"]
    start_urls = ['https://albertacannabis.org/login/']

    def parse(self, response):
        csrf_token = response.xpath('//*[@name="__RequestVerificationToken"]/@value').extract()[0]

        yield FormRequest('https://albertacannabis.org/api/cxa/LoginExtended/LoginAglc/',
                            formdata={'__RequestVerificationToken' : csrf_token,
                                        'UserName': 'test',
                                        'Password' : 'test'},
                            callback=self.parse_after_login)

    def parse_after_login(self, response):
        if response.xpath('//a[text()="Log Out"]'):
            print 'Success'

这就是我从Scrapy得到的

2018-11-07 14:23:55 [scrapy.utils.log] INFO: Scrapy 1.5.1 started (bot: canna_spider)
2018-11-07 14:23:55 [scrapy.utils.log] INFO: Versions: lxml 4.2.5.0, libxml2 2.9.8, cssselect 1.0.3, parsel 1.5.1, w3lib 1.19.0, Twisted 18.7.0, Python 2.7.15 |Anaconda, Inc.| (default, May  1 2018, 18:37:09) [MSC v.1500 64 bit (AMD64)], pyOpenSSL 18.0.0 (OpenSSL 1.0.2p  14 Aug 2018), cryptography 2.3.1, Platform Windows-10-10.0.17134
2018-11-07 14:23:55 [scrapy.crawler] INFO: Overridden settings: {'NEWSPIDER_MODULE': 'canna_spider.spiders', 'SPIDER_MODULES': ['canna_spider.spiders'], 'BOT_NAME': 'canna_spider'}
2018-11-07 14:23:55 [scrapy.middleware] INFO: Enabled extensions:
['scrapy.extensions.logstats.LogStats',
 'scrapy.extensions.telnet.TelnetConsole',
 'scrapy.extensions.corestats.CoreStats']
2018-11-07 14:23:55 [scrapy.middleware] INFO: Enabled downloader middlewares:
['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.httpproxy.HttpProxyMiddleware',
 'scrapy.downloadermiddlewares.stats.DownloaderStats']
2018-11-07 14:23:55 [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']
2018-11-07 14:23:55 [scrapy.middleware] INFO: Enabled item pipelines:
[]
2018-11-07 14:23:55 [scrapy.core.engine] INFO: Spider opened
2018-11-07 14:23:55 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2018-11-07 14:23:55 [scrapy.extensions.telnet] DEBUG: Telnet console listening on 127.0.0.1:6024
2018-11-07 14:23:55 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://albertacannabis.org/login/> (referer: None)
2018-11-07 14:23:55 [scrapy.core.engine] DEBUG: Crawled (200) <POST https://albertacannabis.org/api/cxa/LoginExtended/LoginAglc/> (referer: https://albertacannabis.org/login/)
2018-11-07 14:23:56 [scrapy.core.engine] INFO: Closing spider (finished)
2018-11-07 14:23:56 [scrapy.statscollectors] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 994,
 'downloader/request_count': 2,
 'downloader/request_method_count/GET': 1,
 'downloader/request_method_count/POST': 1,
 'downloader/response_bytes': 8316,
 'downloader/response_count': 2,
 'downloader/response_status_count/200': 2,
 'finish_reason': 'finished',
 'finish_time': datetime.datetime(2018, 11, 7, 19, 23, 56, 77000),
 'log_count/DEBUG': 3,
 'log_count/INFO': 7,
 'request_depth_max': 1,
 'response_received_count': 2,
 'scheduler/dequeued': 2,
 'scheduler/dequeued/memory': 2,
 'scheduler/enqueued': 2,
 'scheduler/enqueued/memory': 2,
 'start_time': datetime.datetime(2018, 11, 7, 19, 23, 55, 547000)}
2018-11-07 14:23:56 [scrapy.core.engine] INFO: Spider closed (finished)

1 个答案:

答案 0 :(得分:0)

我已经登录,只是没有重定向到主页,这里是稍作更新的代码:

# -*- coding: utf-8 -*-
import scrapy
from scrapy.http import FormRequest
from scrapy.shell import inspect_response

class LoginSpider(scrapy.Spider):
   name = "login"
   allowed_domains = ["albertacannabis.org"]
   start_urls = ['https://albertacannabis.org/']

def parse(self, response):
    csrf_token = response.xpath('//*[@name="__RequestVerificationToken"]/@value').extract()[0]

    yield FormRequest('https://albertacannabis.org/api/cxa/LoginExtended/LoginAglc',
                        formdata={'__RequestVerificationToken' : csrf_token,
                                  'UserName': 'test@gmail.com',
                                  'Password' : '12345678',
                                  'X-Requested-With': 'XMLHttpRequest'},
                        callback=self.parse_after_login)

def parse_after_login(self, response):
    yield scrapy.Request('https://albertacannabis.org/',
                  callback=self.parse_home_page)

def parse_home_page(self, response):
    if response.xpath('//a[text()="Log Out"]'):
        print('Success')