Как получить session_id при использовании скрипта Crawlera lua в Scrapy Splash? - PullRequest
0 голосов
/ 27 ноября 2018

Как вы знаете, мы используем этот скрипт lua, когда пытаемся использовать Scrapy Splash с Crawlera:

function use_crawlera(splash)
    -- Make sure you pass your Crawlera API key in the 'crawlera_user' arg.
    -- Have a look at the file spiders/quotes-js.py to see how to do it.
    -- Find your Crawlera credentials in https://app.scrapinghub.com/
    local user = splash.args.crawlera_user

    local host = 'proxy.crawlera.com'
    local port = 8010
    local session_header = 'X-Crawlera-Session'
    local session_id = 'create'

    splash:on_request(function (request)
        request:set_header('X-Crawlera-Cookies', 'disable')
        request:set_header(session_header, session_id)
        request:set_proxy{host, port, username=user, password=''}
    end)

    splash:on_response_headers(function (response)
        if type(response.headers[session_header]) ~= nil then
            session_id = response.headers[session_header]
        end
    end)
end

function main(splash)
    use_crawlera(splash)
        splash:init_cookies(splash.args.cookies)
        assert(splash:go{
            splash.args.url,
            headers=splash.args.headers,
            http_method=splash.args.http_method,
        })    
            assert(splash:wait(3))
        return {
            html = splash:html(),
            cookies = splash:get_cookies(),
        }
end

В этом скрипте lua есть переменная session_id, которая мне очень нужна, но как я могуЯ получаю доступ к нему из ответа Scrapy?

Я пробовал response.session_id или response.headers['X-Crawlera-Session'], но оба не работают.

Ответы [ 2 ]

0 голосов
/ 06 июля 2019
  1. Также возвращает данные HAR (https://splash.readthedocs.io/en/stable/scripting-ref.html#splash-har) в вашем скрипте lua:
    return {
        html = splash:html(),
        har = splash:har(),
        cookies = splash:get_cookies(),
    }
Если вы используете scrapy-splash (https://github.com/scrapy-plugins/scrapy-splash), убедитесь, что вы установили конечную точку execute для своего запроса:

meta['splash']['endpoint'] = 'execute'.

Если вы используете scrapy.Request, то render.json является конечной точкой по умолчанию, но для scrapy_splash.SplashRequest конечной точкой по умолчанию является render.html. Посмотрите эти 2 примера, чтобы узнать, как установить конечную точку: https://github.com/scrapy-plugins/scrapy-splash#requests

Только теперь у вас есть доступ к заголовку X-Crawlera-Session в вашем методе разбора:
    def parse(self, response):
        headers = json.loads(response.text)['har']['log']['entries'][0]['response']['headers']
        session_id = next(x for x in headers if x['name'] == 'X-Crawlera-Session')['value']
>>> headers = json.loads(response.text)['har']['log']['entries'][0]['response']['headers']
>>> next(x for x in headers if x['name'] == 'X-Crawlera-Session')
{u'name': u'X-Crawlera-Session', u'value': u'2124641382'}
0 голосов
/ 05 июля 2019

Использование splash: set_result_header .

...