2015-04-05 19 views
0

我一直很努力,但我不能讓這個網頁上這些特定鏈接: http://www.windowsphone.com/en-us/store/top-free-apps 我想在這個頁面左側的鏈接中的每一個,娛樂例如,但我不能找到合適的參考獲取它們。 它的腳本:如何提取這些在Ruby中使用機械化的特定鏈接?

require 'mechanize' 
agent = Mechanize.new 
page = agent.get("http://www.windowsphone.com/en-us/store/top-free-apps") 
page.links_with(???) 

我應該怎麼放,而不是???所以我不能得到這些鏈接? 我試過的東西,如:

page.links_with(:class => 'categoryNav navText') 

OR

page.links_with(:class => 'categoryNav') 

OR

page.links_with(:class => 'navText') 

等 誰能幫助嗎?

回答

0

使用page.parser,您可以訪問底層的Nokogiri對象。這使您可以使用xpath進行搜索。

這裏的想法是所有這些鏈接都有一個以'AppLeftMerch'開頭的'data-ov'屬性。這是我們可以使用'starts-with'功能識別它們的東西。

require 'mechanize' 

agent = Mechanize.new 
page = agent.get("http://www.windowsphone.com/en-us/store/top-free-apps") 

page.parser.xpath("//a[starts-with(@data-ov,'AppLeftMerch')]").each do |link| 
    puts link[:href] 
end