2016-03-02 49 views
-1

我是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 
+0

您正在嘗試迭代帳單活動記錄集合中的每個項目嗎?你確定它包含每個迭代的記錄嗎? –

+0

不,我實際上遍歷了'doc'變量,我使用'open-uri'返回: –

+0

yes根據您的查詢[bills = doc.xpath(「// p [@ align ='left']/font [@ size ='2']「)]如果你的代碼工作正常,那麼變量賬單將包含一個集合,所以只需調試bills變量來檢查它是否包含任何記錄集合。 –

回答

0

想通了。

當我通過我的bills變量創建時,我在xpath中的深度不夠(我認爲)...我將bills變量更改爲等於doc.xpath("//p/font/a")並且工作正常。

+0

仍然不完全確定爲什麼,所以我完全接受解釋。 :) –

0

你的代碼告訴你,你正試圖調用一個方法在一個零的對象上。爲什麼它是零是你必須在時間允許的情況下進行調試。

但是,通過一些重構,您可以修復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視圖。

相關問題