为什么 bill.xpath("//p/font/a")[index].text return "undefined method `text' for nil:NilClass" 使用 Nokogiri?

Why does bill.xpath("//p/font/a")[index].text return "undefined method `text' for nil:NilClass" using Nokogiri?

我是Ruby的新手,所以如果这是一个简单的问题,请原谅我。

我在这段代码中遇到了上述错误:

bills = doc.xpath("//p[@align='left']/font[@size='2']")
@billsArray = []
bills.each_with_index do |bill, index|
  title = bill.xpath("//p/font/a")[index].text
  link  = bill.xpath("//p/font/a")[index]['href']
  @billsArray << Bill.new(title, link)
end

我想做的是遍历我从 xpath 通话中取回的项目并显示每一个...似乎没有用。

如果我从我的标题变量中取出 index,我会得到这个错误:undefined method '[]' for nil:NilClass。根据错误中的 [],我假设 [index] 实际上没有返回值...我设置循环的方式没有问题吗?

最终目标是在此页面上显示所有 link 的 link 和 link 文本:http://billstatus.ls.state.ms.us/2016/pdf/misc/h_cal.htm

这是文件的完整代码:

    class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception

  class Bill
    def initialize(title, link)
      @title  = title
      @link   = link
    end
    attr_reader :title
    attr_reader :link
  end

  def scrape_house_calendar
    # Pull in the page
    require 'open-uri'
    doc = Nokogiri::HTML(open("http://billstatus.ls.state.ms.us/2016/pdf/misc/h_cal.htm"))

    # Narrow down what we want and build the bills array
    bills = doc.xpath("//p[@align='left']/font[@size='2']")
    @billsArray = []
    bills.each_with_index do |bill, index|
      title = bill.xpath("//p/font/a")[index].text
      link  = bill.xpath("//p/font/a")[index]['href']
      @billsArray << Bill.new(title, link)
    end

    # Render the bills array
    render template: 'scrape_house_calendar'
  end
end

想通了。

当我用我的 bills 变量创建时,我在 xpath 中不够深入(我认为)...我将我的 bills 变量更改为等于 doc.xpath("//p/font/a")它奏效了。

您的代码告诉您您正试图在一个为 nil 的对象上调用一个方法。为什么它为零是您必须在时间允许的情况下进行调试的原因。

但是,通过一些重构,您可以修复 XPath 并将所有节点结果压缩到一个数组数组中,而无需所有索引。例如:

require 'open-uri'
require 'nokogiri'

url = 'http://billstatus.ls.state.ms.us/2016/pdf/misc/h_cal.htm'
doc = Nokogiri::HTML(open url)
@bills =
  doc.xpath("//p[@align='left']/font[@size='2']").map do |node|
    node.xpath("//p/font/a/text()").map { |tnode| tnode.text.strip }.zip \
    node.xpath("//p/font/a/@href").map(&:to_s)
  end.first

@bills.first
#=> ["H. B. No.  899:", "../../../2016/PDF/history/HB/HB0899.xml"]

然后您可以按照自己喜欢的方式转换数组,然后再将其输入 Rails 视图。