Python scrapy - 登录验证问题

时间:2016-06-15 16:54:49

标签: python web-scraping scrapy web-crawler scrapy-spider

我刚开始使用scrapy。我在scrapy登录时遇到的问题很少。我正在尝试网站www.instacart.com上的scrape项目。但我遇到登录问题。

以下是代码

import scrapy

from scrapy.loader import ItemLoader
from project.items import ProjectItem
from scrapy.http import Request
from scrapy import optional_features
optional_features.remove('boto')

class FirstSpider(scrapy.Spider):
    name = "first"
    allowed_domains = ["https://instacart.com"]
    start_urls = [
        "https://www.instacart.com"
    ]

    def init_request(self):
        return Request(url=self.login_page, callback=self.login)

    def login(self, response):
        return scrapy.FormRequest('https://www.instacart.com/#login',
                                     formdata={'email': 'xxx@xxx.com', 'password': 'xxxxxx',
                                               },
                                     callback=self.parse)

    def check_login_response(self, response):
        return scrapy.Request('https://www.instacart.com/', self.parse)

    def parse(self, response):
        if "Goutam" in response.body:
            print "Successfully logged in. Let's start crawling!"
        else:
            print "Login unsuccessful"

以下是错误消息

    C:\Users\gouta\PycharmProjects\CSG_Scraping\csg_wholefoods>scrapy crawl first
2016-06-15 10:44:50 [scrapy] INFO: Scrapy 1.0.3 started (bot: project)
2016-06-15 10:44:50 [scrapy] INFO: Optional features available: ssl, http11
2016-06-15 10:44:50 [scrapy] INFO: Overridden settings: {'NEWSPIDER_MODULE': 'project.spiders', 'SPIDER_MODULES': ['project.spiders'], 'ROBOTSTXT_OBEY': True, 'BOT_NAME': 'project'}
2016-06-15 10:44:50 [scrapy] INFO: Enabled extensions: CloseSpider, TelnetConsole, LogStats, CoreStats, SpiderState
2016-06-15 10:44:50 [scrapy] INFO: Enabled downloader middlewares: RobotsTxtMiddleware, HttpAuthMiddleware, DownloadTimeoutMiddleware, UserAgentMiddleware, RetryMiddleware, DefaultHeadersMiddleware, MetaRefreshMiddleware, HttpCompressionMiddleware, RedirectMiddleware, CookiesMiddleware, ChunkedTransferMiddleware, DownloaderStats
2016-06-15 10:44:51 [scrapy] INFO: Enabled spider middlewares: HttpErrorMiddleware, OffsiteMiddleware, RefererMiddleware, UrlLengthMiddleware, DepthMiddleware
2016-06-15 10:44:51 [scrapy] INFO: Enabled item pipelines:
2016-06-15 10:44:51 [scrapy] INFO: Spider opened
2016-06-15 10:44:51 [scrapy] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2016-06-15 10:44:51 [scrapy] DEBUG: Telnet console listening on 127.0.0.1:6023
2016-06-15 10:44:51 [scrapy] DEBUG: Crawled (200) <GET https://www.instacart.com/robots.txt> (referer: None)
2016-06-15 10:44:51 [scrapy] DEBUG: Crawled (200) <GET https://www.instacart.com> (referer: None)
Login unsuccessful
2016-06-15 10:44:51 [scrapy] INFO: Closing spider (finished)
2016-06-15 10:44:51 [scrapy] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 440,
 'downloader/request_count': 2,
 'downloader/request_method_count/GET': 2,
 'downloader/response_bytes': 17182,
 'downloader/response_count': 2,
 'downloader/response_status_count/200': 2,
 'finish_reason': 'finished',
 'finish_time': datetime.datetime(2016, 6, 15, 15, 44, 51, 767000),
 'log_count/DEBUG': 3,
 'log_count/INFO': 7,
 'response_received_count': 2,
 'scheduler/dequeued': 1,
 'scheduler/dequeued/memory': 1,
 'scheduler/enqueued': 1,
 'scheduler/enqueued/memory': 1,
 'start_time': datetime.datetime(2016, 6, 15, 15, 44, 51, 31000)}
2016-06-15 10:44:51 [scrapy] INFO: Spider closed (finished)

对我所做错的任何建议都非常感谢。

1 个答案:

答案 0 :(得分:5)

如果你查看帖子数据,你可以看到帖子的字段:

enter image description here

headers = {"X-Requested-With":"XMLHttpRequest"}
formdata = {'user[email]': 'xxx@xxx.com', 'user[password]': 'xxxx',
            "authenticity_token":response.xpath("//meta[@csrf-token]/@content").extract_first()}

实际上还有一些问题,一个完整的蜘蛛:

from scrapy.crawler import CrawlerProcess
import scrapy

from scrapy.http import Request

class FirstSpider(scrapy.Spider):
    name = "first"
    allowed_domains = ["instacart.com"]
    start_urls = [
        "https://www.instacart.com"
    ]

    def start_requests(self):
        return [Request(url="https://www.instacart.com", callback=self.login)]

    def login(self, response):
        return scrapy.FormRequest('https://www.instacart.com/accounts/login',
                                  headers={"X-Requested-With": "XMLHttpRequest"},
                                  formdata={'user[email]': 'xxxxxxx@gmail.com', 'user[password]': 'xxxxx',
                                            "authenticity_token": response.xpath(
                                                "//meta[@name='csrf-token']/@content").extract_first()},
                                  callback=self.parse,dont_filter=True)


    def parse(self, response):
        print(response.body)
        if "Goutam" in response.body:
            print "Successfully logged in. Let's start crawling!"
        else:
            print "Login unsuccessful"

现在唯一的问题是很多内容都是使用react加载的。