2

我正在使用 Python、Scrapy、Splash 和 scrapy_splash 包来废弃网站。

我可以使用 scrapy_splash 中的 SplashRequest 对象登录。登录会创建一个 cookie,让我可以访问门户页面。至此,一切正常。

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

我对 SplashRequest 尝试了相同的方法,但是,我无法捕获随重定向返回的 SSO 查询参数。我试图读取标头 Location 参数但没有成功。

我还尝试将 lua 脚本与 SplashRequest 对象结合使用,但是,我仍然无法访问重定向 Location 对象。

任何指导将不胜感激。

我意识到还有其他可用的解决方案(即硒),但是上述技术是我们在大量其他脚本中使用的技术,我不愿为这个特定用例添加新技术。

# Lua script to capture cookies and SSO query parameter from 302 Redirect
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')
4

1 回答 1

1

我用一个工作示例更新了上面的问题。

我改变了一些东西,但是我遇到的问题与缺少参考直接相关splash:init_cookies(splash.args.cookies)

我还从 using 转换SplashFormRequestSplashRequest,重构了splash:go块并删除了对特定表单的引用。

再次感谢@MikhailKorobov 的帮助。

于 2017-05-19T09:52:07.553 回答