如何使用 scrapy_splash 包在表单提交后进行重定向?

我正在使用 Python、Scrapy、Splash 和 scrapy_splash 包来爬取一个网站。

我能够使用 scrapy_splash 中的 SplashRequest 对象登录。 登录后会创建一个 cookie,使我能够访问门户页面。到这一步都没问题。

在门户页面上,有一个包含许多按钮的表单元素。点击时会更新操作 URL 并触发表单提交。表单提交会导致 302 重定向。

我尝试使用 SplashRequest 来进行相同的处理,然而,我无法捕获重定向时返回的 SSO 查询参数。我尝试读取 Location 参数的头信息,但是不成功。

我还尝试使用 lua 脚本结合 SplashRequest 对象,然而,仍然无法访问重定向位置对象。

任何指导都将不胜感激。

我知道还有其他解决方案(比如 selenium),但是上述技术是我们在许多其他脚本中使用的,我不想为这个具体的用例添加新技术。

# Lua 脚本用于从 302 重定向中捕获 cookies 和 SSO 查询参数
lua_script = """
    function main(splash)
        if splash.args.cookies then
            splash:init_cookies(splash.args.cookies)
        end
        assert(splash:go{
            splash.args.url,
            headers=splash.args.headers,
            http_method=splash.args.http_method,
            body=splash.args.body,
            formdata=splash.args.formdata
        })
        assert(splash:wait(0))

        local entries = splash:history()
        local last_response = entries[#entries].response

        return {
            url = splash:url(),
            headers = last_response.headers,
            http_status = last_response.status,
            cookies = splash:get_cookies(),
            html = splash:html(),
        }
    end
    """

def parse(self, response):
    yield SplashRequest(
    url='https://members.example.com/login',
    callback=self.portal_page,
    method='POST',
    endpoint='execute',
    args={
        'wait': 0.5,
        'lua_source': self.lua_script,
        'formdata': {
            'username': self.login,
            'password': self.password
        },
    }
)

def portal_page(self, response):
    yield SplashRequest(
    url='https://data.example.com/portal'
    callback=self.data_download,
    args={
        'wait': 0.5,
        'lua_source': self.lua_script,
        'formdata': {}
    },
)

def data_download(self, response):
    print(response.body.decode('utf8')
点赞
用户607808
用户607808

我已经在上面的问题中更新了一个可工作的示例。然而,我更改了一些内容,但是我遇到的问题直接与缺少splash:init_cookies(splash.args.cookies)引用有关。我还将其从SplashFormRequest转换为SplashRequest,重构了splash:go块并删除了对特定表单的引用。再次感谢@MikhailKorobov的帮助。

2017-05-19 09:52:07