如何解决如何将变量传递给在命令提示符下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)
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。