【问题标题】:Passing a table from a ScrapySplash Lua Script to Python将表从 ScrapySplash Lua 脚本传递到 Python
【发布时间】:2020-07-06 05:27:45
【问题描述】:

我正在运行 ScrapySplash,并尝试将在 Lua 中创建的表传递给 Parse 方法。如果我尝试访问该表,则会收到类型错误消息:“SplashJsonResponse”对象不可下标。

我的 Lua 脚本如下:

    script = '''
            function main(splash, args)
              assert(splash:go(args.url))
              assert(splash:wait(0.5))
              img = {}
              for i=1,5 do 
                table.insert(img, "Testing")
              end


              return {
                html = splash:html(),
                png = splash:png(),
                har = splash:har(),
                img,
              }
            end
    '''

那么我的解析方法就是:

    def parse_item(self, response):
        images = response['img']
        print (images)

但是,如上所述,这只会在 images = response['img'] 行上给我一个错误,说 'SplashJsonResponse' object is not subscriptable'。

有人知道我如何在 parse 方法中访问这个 Lua 表中的值吗?

谢谢

【问题讨论】:

    标签: python lua scrapy scrapy-splash


    【解决方案1】:

    好吧,我以某种方式解决了这个问题,但我不知道如何解决。基本上我改变了我的lua语句中的return语句如下:

        script = '''
                function main(splash, args)
                  assert(splash:go(args.url))
                  assert(splash:wait(0.5))
                  img = {}
                  for i=1,5 do 
                    table.insert(img, "Testing")
                  end
    
    
                  return {
                    html = splash:html(),
                    png = splash:png(),
                    har = splash:har(),
                    img,
                  }
                end
        '''
    

    然后在我的解析方法中,我有以下内容:

        def parse(self, response):
            images = (response.data['a'])
    

    现在我有一个名为 images 的字典,可以通过 images['i'] 访问每个变量,虽然我不知道为什么会这样,但我原来的方法没有。如果有人理解为什么,请随时发表评论并告诉我。谢谢

    【讨论】:

      【解决方案2】:

      出现错误'SplashJsonResponse' object is not subscriptable' 是因为您尝试在没有data 密钥的情况下从字典响应中访问密钥。

      不正确:response['some_key_from_dictionary']

      正确:不正确:response.data['some_key_from_dictionary']

      【讨论】:

        猜你喜欢
        • 2012-05-27
        • 2013-07-24
        • 2011-06-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-28
        • 2011-01-14
        相关资源
        最近更新 更多