使用Nokogiri从Ruby网页中抓取元素

bjp0bcyl  于 2023-05-17  发布在  Ruby
关注(0)|答案(1)|浏览(253)

描述有一个网页,加载到Mechanize ruby gem中。问题是,我可以在开发人员工具中看到HTML片段,但无法提取元素和相关文本。

页面上的HTML片段,嵌套在一系列标签中,如下所示:

<button stid="FLIGHTS_DETAILS_AND_FARES" data-test-id="select-link" data-stid="FLIGHTS_DETAILS_AND_FARES-index-1" class="uixtk-card-link" type="button"><span class="is-visually-hidden">Select and show fare information for flight, departing at 6:40 am from Somewhere, arriving at 12:35 pm in Somewhere, Priced at $683 Return per traveller.  6 hours 25 minutes total travel time, One stop, Stopover for 1 hour 40 minutes in Another Place.</span></button>

我试图提取文本内容的描述,时间,行程长度和成本。
下面显示了简单的ruby测试代码(注意实际的站点细节被删除了),它简单地设置了Mechanize并调用了PRY,以便可以对其进行测试。

require 'mechanize'
require 'nokogiri'
require 'open-uri'
require 'pry'

class Mecho 

    site_url = 'https://host.com'

    agent = Mechanize.new 

    page = agent.get(site_url)

    binding.pry
end

给出上面的HTML代码片段,我尝试通过

page.css("button")

虽然这定位了很多按钮标记的网页上似乎无法找到片段后,我。
然后我尝试定位通过<span class="is-visually-hidden">标识的元素,它给了我17个条目,但仍然没有找到我要找的那个。
我已经检查了Nokogiri cheat sheet,看看是否还有其他我遗漏的方法。目前还没找到

au9on6nz

au9on6nz1#

就像

page.css("button.uixtk-card-link")

page.css("button.is-visually-hidden")

应该能找到
如果页面是动态的,那么请确保在调用Nokogiri时该元素存在。

相关问题