[英](Rails) Can't get Mechanize to correctly read a web xml file
我必須閱讀可通過帶有身份驗證的http訪問的xml文件。 這就是為什么我使用機械化。
我的問題是我無法機械地識別這些XML文件,因此可以對它們使用.find或.search。
這是我首先嘗試的方法-在我看來(HTML文件)
<% agent = Mechanize.new %>
<% page = agent.get("http://dl.dropbox.com/u/344349/xml.xml") %>
<%= page %>
返回#<Mechanize::File:0x007f9dd602de30>
。 它是::File
而不是::Page
我不能對此使用.find或.search,因為它會undefined method find for #<Mechanize::File:0x007f9dd624cbd0>
出錯
Mechanize doc說:這是可插拔解析器的默認(和基本)類。 如果Mechanize無法找到適合於內容類型的類,則將使用該類。 例如,如果下載JPG,Mechanize將不知道如何解析它,因此將實例化此類。
所以我創建了一個如下所述的類: http : //rdoc.info/github/tenderlove/mechanize/master/Mechanize/PluggableParser
My class
class XMLParser < Mechanize::File
attr_reader :xml
def initialize(uri=nil, response=nil, body=nil, code=nil)
super(uri, response, body, code)
@xml = xml.parse(body)
end
end
和我視圖中的更新代碼(html文件)
<% agent = Mechanize.new %>
<% agent.pluggable_parser['text/xml'] = XMLParser %>
<% agent.user_agent_alias = 'Windows Mozilla' %>
<% page = agent.get("http://dl.dropbox.com/u/344349/xml.xml") %>
<%= page %>
甚至
<% agent = Mechanize.new %>
<% agent.pluggable_parser.xml = XMLParser %>
<% page1 = agent.get('http://dl.dropbox.com/u/344349/xml.xml') # => CSVParser %>
<%= page1 %>
仍返回#<Mechanize::File:0x007f9dd5253b48>
我什至測試了確切的代碼(CSVParser- http: //rdoc.info/github/tenderlove/mechanize/master/Mechanize/PluggableParser),並嘗試加載仍被視為:: File的csv文件。
我究竟做錯了什么 ?
好的,現在我已經為自己解決了這個問題。 解決方案分為兩部分:
首先,您要匹配的內容類型不正確。 如果運行此行,獲取后,它將告訴您所獲取文檔的內容類型是什么:
page.response['content-type'] # => 'application/xml', not 'text/xml'
當我使用機械化方法獲取您的頁面(“ http://dl.dropbox.com/u/344349/xml.xml”)時,我看到“ application / xml”作為內容類型。
其次,您沒有正確使用PluggableParser。 在這里使用XMLParser會生成NoMethodError: undefined method 'parse' for nil:NilClass
。 將類定義更改為使用Nokogiri :: XML代替:
class XmlParser < Mechanize::File
attr_reader :xml
def initialize(uri = nil, response = nil, body = nil, code = nil)
@xml = Nokogiri::XML(body)
super uri, response, body, code
end
end
然后,將其設置為正確內容類型的解析器:
mech.pluggable_parser['application/xml'] = XmlParser
要使用它,您將獲得與以前相同的頁面,然后將頁面對象的xml屬性作為Nokogiri :: XML :: Document實例引用,該實例是Nokogiri :: XML :: Node的子類。 幸運的是, Mechanize :: Page.search只是Nokogiri :: XML :: Node.search的包裝,因此您幾乎可以按照您期望的方式進行搜索。 像這樣:
page.xml.search 'catalog'
進一步的改進是將XmlParser.search映射到Nokogiri .search方法:
# This is the same as what Mechanize::Page does
class XmlParser < Mechanize::File
extend Forwardable
def_delegators :@xml, :search, :/, :at
end
這使您可以直接在頁面實例上執行搜索:
page.search 'catalog'
您可以將解析器更改為使用Page類,如下所示:
agent = Mechanize.new
agent.pluggable_parser.default = Mechanize::Page
agent.get("http://dl.dropbox.com/u/344349/xml.xml").class # Mechanize::Page
參見http://mechanize.rubyforge.org/Mechanize/PluggableParser.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.