Python scrapy - 登录身份验证问题 [英] Python scrapy - Login Authenication Issue

查看:89
本文介绍了Python scrapy - 登录身份验证问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始使用scrapy.我在scrapy中登录时遇到了一些问题.我正在尝试 www.instacart.com 网站上的刮擦项目.但我在登录时遇到了问题.

I have just started using scrapy. I am facing few problems with login in scrapy. I am trying the scrape items in the website www.instacart.com. But I am facing issues with logging in.

以下是代码

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)

对我做错的任何建议表示高度赞赏.

Any advice on what I am doing wrong is highly appreciated.

推荐答案

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

if you look at the post data, you can see the fields for the post:

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

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

There are actually a few more issues, a full working spider:

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 加载的.

The only issue now is a lot of the content is loaded using react.

这篇关于Python scrapy - 登录身份验证问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆