我是Ruby新手,所以請原諒我,如果這是一個簡單的問題。爲什麼bill.xpath(「// p/font/a」)[index] .text使用Nokogiri返回「nil:NilClass」的未定義方法「text」?
,我發現了上面的錯誤與下面的代碼塊:
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]
實際上並沒有返回值...在我設置循環的方式中沒有出錯?
的最終目標是要顯示此網頁上所有鏈接的鏈接&鏈接文字: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
您正在嘗試迭代帳單活動記錄集合中的每個項目嗎?你確定它包含每個迭代的記錄嗎? –
不,我實際上遍歷了'doc'變量,我使用'open-uri'返回: –
yes根據您的查詢[bills = doc.xpath(「// p [@ align ='left']/font [@ size ='2']「)]如果你的代碼工作正常,那麼變量賬單將包含一個集合,所以只需調試bills變量來檢查它是否包含任何記錄集合。 –