如何使用scrapy_splash包重定向表单后?

时间:2017-05-18 10:56:00

标签: python lua scrapy splash scrapy-splash

我使用Python,Scrapy,Splash和scrapy_splash软件包来废弃网站。

我可以使用scrapy_splash中的SplashRequest对象登录。 登录创建一个cookie,使我可以访问门户页面。到目前为止一切都有效。

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

我尝试使用SplashRequest采用相同的方法,但是,我无法捕获随重定向返回的SSO查询参数。我试图读取标题位置参数但没有成功。

我还尝试将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')

1 个答案:

答案 0 :(得分:1)

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

我更改了一些内容但是我遇到的问题与错过splash:init_cookies(splash.args.cookies)引用直接相关。

我也从使用SplashFormRequest转换为SplashRequest,重构了splash:go块并删除了对特定表单的引用。

再次感谢@MikhailKorobov的帮助。

相关问题