【问题标题】:How to loop through an table and turn rows into objects using nokogiri如何使用 nokogiri 遍历表并将行转换为对象
【发布时间】:2010-11-10 01:42:26
【问题描述】:

我想使用 nokogiri 循环遍历一个 html 并创建一个对应于每一行的对象。我能够定义我希望数据填充对象变量的根 xpath,但我不知道如何将它们分组为对象。

我的代码如下。我知道这行不通,但我不知道要让它发挥作用。

需要“红宝石” 需要'nokogiri'

doc = Nokogiri::HTML.parse(

类帖子 定义初始化(v1,v2,v3) @v1 =v1 @v2 = v2 @v3 = v3 结束

  def v1= (v1)
    @v1 =v1
  end

  def v2
    @v2 =v2
  end

  def v3
    @v3 =v3
  end

结束

类 PostList 定义初始化 @posts = Array.new 结束

    def append(aPost)
      @posts.push(aPost)
      self
    end

    def deleteFirst
      @posts.shift
    end

    def deleteLast
      @posts.pop
    end

结束

list = PostList.new

parent = doc.css('body').first

获取行的内容

parent.xpath("//div/table[@class='ipbtable']/tr" ).each 做|a_tag|

k1 = "x" k2 = "x" k3 = "x"

a_tag.xpath("td[1]").each 做 |x_tag|

放置 x_tag.content

结束

list.append(Post.new(k1, k2, k3))

结束

【问题讨论】:

    标签: ruby nokogiri loops


    【解决方案1】:

    代码的主要问题似乎是您传递的字符串 ('K1', 'K2', 'K3') 模糊地类似于变量的名称,而不是变量本身 (k1, k2, k3)。但是,您可以更简洁地将其表达为:

    doc.search('table > tr').each do |row|
      properties = row.search('td/text()').collect {|text| text.to_s}
      list.append Post.new(*properties)
    end
    

    这只是遍历每一行并使用该行中每个 td 的文本内容创建一个 Post。

    【讨论】:

      猜你喜欢
      • 2021-12-15
      • 1970-01-01
      • 1970-01-01
      • 2018-05-20
      • 1970-01-01
      • 1970-01-01
      • 2019-01-18
      • 2022-01-15
      • 1970-01-01
      相关资源
      最近更新 更多