1

我设法使用scrapy+splash 连接到一个网站(感谢这个线程)。

我知道我已登录,因为我可以显示一些您登录后可用的元素。但是,当我尝试使用另一个页面访问另一个页面时SplashRequest,网站会要求再次登录。

所以看起来scrapy(或splash)并没有保持会话活跃。为了保持登录状态并保持会话处于活动状态,是否需要启用某些功能?

谢谢,

4

1 回答 1

2

Splash 从一个干净的状态开始每个渲染,所以如果你想保持会话,你需要首先初始化 cookie,并且还要让 Scrapy 知道在渲染过程中设置的 cookie。请参阅scrapy-splash README 中的会话处理部分。一个完整的示例可能如下所示(从 README 复制粘贴):

import scrapy
from scrapy_splash import SplashRequest

script = """
function main(splash)
  splash:init_cookies(splash.args.cookies)
  assert(splash:go{
    splash.args.url,
    headers=splash.args.headers,
    http_method=splash.args.http_method,
    body=splash.args.body,
    })
  assert(splash:wait(0.5))

  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
"""

class MySpider(scrapy.Spider):


    # ...
        yield SplashRequest(url, self.parse_result,
            endpoint='execute',
            cache_args=['lua_source'],
            args={'lua_source': script},
        )

    def parse_result(self, response):
        # here response.body contains result HTML;
        # response.headers are filled with headers from last
        # web page loaded to Splash;
        # cookies from all responses and from JavaScript are collected
        # and put into Set-Cookie response header, so that Scrapy
        # can remember them.

请注意,会话当前需要使用 /execute 或 /run 端点,其他端点没有帮助程序。

于 2017-07-26T21:31:05.370 回答