Cas*_*per 4 python scrapy scrapy-splash splash-js-render
我在使用 Splash 发出请求后尝试访问 cookie。以下是我构建请求的方式。
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
"""
req = SplashRequest(
url,
self.parse_page,
args={
'wait': 0.5,
'lua_source': script,
'endpoint': 'execute'
}
)
Run Code Online (Sandbox Code Playgroud)
该脚本是 Splash 文档的精确副本。
所以我试图访问网页上设置的cookie。当我不使用 Splash 时,下面的代码将按我的预期工作,但在使用 Splash 时则不然。
self.logger.debug('Cookies: %s', response.headers.get('Set-Cookie'))
Run Code Online (Sandbox Code Playgroud)
使用 Splash 时会返回:
2017-01-03 12:12:37 [蜘蛛] 调试:Cookies:无
当我不使用 Splash 时,此代码可以工作并返回网页提供的 cookie。
Splash 的文档显示了此代码作为示例:
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.
Run Code Online (Sandbox Code Playgroud)
我不确定我是否理解正确,但我想说我应该能够以与不使用 Splash 时相同的方式访问 cookie。
中间件设置:
# Download middlewares
DOWNLOADER_MIDDLEWARES = {
# Use a random user agent on each request
'crawling.middlewares.RandomUserAgentDownloaderMiddleware': 400,
'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware': None,
'scrapy.downloadermiddlewares.cookies.CookiesMiddleware': 700,
# Enable crawlera proxy
'scrapy_crawlera.CrawleraMiddleware': 600,
# Enable Splash to render javascript
'scrapy_splash.SplashCookiesMiddleware': 723,
'scrapy_splash.SplashMiddleware': 725,
'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware': 810,
}
Run Code Online (Sandbox Code Playgroud)
所以我的问题是:如何在使用 Splash 请求时访问 cookie?
您可以设置SPLASH_COOKIES_DEBUG=True
选项来查看正在设置的所有 cookie。当前的 cookiejar 已合并所有 cookie,只要response.cookiejar
配置scrapy-splash
正确,就可以使用。
使用response.headers.get('Set-Header')
并不健壮,因为在重定向(例如 JS 重定向)的情况下,可能会有多个响应,并且可以在第一个响应中设置 cookie,而脚本仅返回最后一个响应的标头。
我不确定这是否是您遇到的问题;该代码并非 Splash 文档的精确副本。这里:
req = SplashRequest(
url,
self.parse_page,
args={
'wait': 0.5,
'lua_source': script
}
)
Run Code Online (Sandbox Code Playgroud)
您正在向/render.json
端点发送请求;它不执行Lua脚本;用来endpoint='execute'
解决这个问题。
归档时间: |
|
查看次数: |
3648 次 |
最近记录: |