如何在使用Scrapy Splash的Crawlera lua脚本中获取session_id?
2018-11-27 15:13:0
收藏:0
阅读:88
评论:2
正如您所知,当我们尝试使用Scrapy Splash和Crawlera时,我们会使用这个Lua脚本:
function use_crawlera(splash)
-- 确保你在 'crawlera_user' 参数中传递了你的Crawlera API密钥。
-- 可以查看文件spiders/quotes-js.py,了解如何执行此操作。
-- 在https://app.scrapinghub.com/中找到你的Crawlera凭据
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']但都不起作用。
点赞
用户3923463
- 在您的 lua 脚本中,同时返回 HAR 数据(https://splash.readthedocs.io/en/stable/scripting-ref.html#splash-har):
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。请参阅这两个示例,了解如何设置端点: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'}
2019-07-06 16:59:29
评论区的留言会收到邮件通知哦~
推荐文章
- Lua 虚拟机加密load(string.dump(function)) 后执行失败问题如何解决
- 我想创建一个 Nginx 规则,禁止访问
- 如何将两个不同的lua文件合成一个 东西有点长 大佬请耐心看完 我是小白研究几天了都没搞定
- 如何在roblox studio中1:1导入真实世界的地形?
- 求解,lua_resume的第二次调用继续执行协程问题。
- 【上海普陀区】内向猫网络招募【Skynet游戏框架Lua后端程序员】
- SF爱好求教:如何用lua实现游戏内调用数据库函数实现账号密码注册?
- Lua实现网站后台开发
- LUA错误显式返回,社区常见的规约是怎么样的
- lua5.3下载库失败
- 请问如何实现文本框内容和某个网页搜索框内容连接,并把网页输出来的结果反馈到另外一个文本框上
- lua lanes多线程使用
- 一个kv数据库
- openresty 有没有比较轻量的 docker 镜像
- 想问一下,有大佬用过luacurl吗
- 在Lua执行过程中使用Load函数出现问题
- 为什么 neovim 里没有显示一些特殊字符?
- Lua比较两个表的值(不考虑键的顺序)
- 有个lua简单的项目,外包,有意者加微信 liuheng600456详谈,最好在成都
- 如何在 Visual Studio 2022 中运行 Lua 代码?

使用splash:set_result_header。