如何将变量传递给在命令提示符下scrapy内部执行的lua脚本?

问题描述

我试图在scrapy中传递一个变量作为用户定义参数,该变量将在lua脚本的for循环中使用,我的代码如下:

How to call the attached callback programmatically event after the component is attached to DOM?

所以,我面临的问题是,当我使用整数(即import scrapy from scrapy_splash import SplashRequest from scrapy.selector import Selector class Productsspider(scrapy.Spider): name = 'allproducts' script = ''' function main(splash,args) assert(splash:go(args.url)) assert(splash:wait(0.5)) result = {} local upto = tonumber(splash.number) for i=1,upto,1 do #something end return output end ''' def start_requests(self): url='https://medicalsupplies.co.uk' yield SplashRequest(url=url,callback=self.parse,endpoint='render.html',args={'wait':0.5}) yield SplashRequest(url=url,callback=self.parse_other_pages,endpoint='execute',args={'wait':0.5,'lua_source':self.script,'number':int(self.number)},dont_filter=True) def parse(self,response): for tr in response.xpath("//table[@id='date']/tbody/tr"): yield{ 'output' : #something } def parse_other_pages(self,response): for page in response.data: sel=Selector(text=page) for tr in sel.xpath("//table[@id='date']/tbody/tr"): yield{ 'output' : #something } )运行lua脚本的for循环时,脚本工作得很好,但是当我尝试从命令中为脚本提供输入时在脚本中使用for i=1,5,1进行for循环的同时使用scrapy crawl allproducts -a number=5 -o test.json提示,我的代码抛出一个错误,我什至不能在该字符串上使用f字符串,是否有办法解决在不破坏代码的情况下将变量传递到文本字符串(此处称为脚本)?我知道我没有使用正确的语法,但是我没有找到相同的任何资源,感谢任何建议。

刮板的实际警告如下:

for i=1,{self.number},1

编辑1:根据@Alexander的建议,修改了lua脚本,并将变量作为整数参数传递给SplashRequest,还使用本地实例化了lua脚本中的变量(local upto = tonumber(splash.number))>

现在的警告如下:

WARNING: Bad request to Splash: {'error': 400,'type': 'ScriptError','description': 'Error happened while executing Lua script','info': {'source': '[string "..."]','line_number': 7,'error': "attempt to index global 'self' (a nil value)",'type': 'LUA_ERROR','message': 'Lua error: [string "..."]:7: attempt to index global \'self\' (a nil value)'}}

解决方法

function main(splash,args)没有self参数。第5行引用了它:for i=1,{self.number},1。而且该函数不是用:声明的方法(函数类型的Lua表的字段),其中self是该表。

您是说splash吗?

我认为,您应该在Python代码('number':self.number)中将args添加到start_requests,然后在Lua脚本中将其称为tonumber(args.number)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...