html - 使用 Nokogiri CSS 方法获取 alt 标签内的所有元素

标签 html css ruby nokogiri

我正在尝试使用 Nokogiri 的 CSS 方法从我的 HTML 中获取一些名称。

这是一个 HTML 示例:

<section class="container partner-customer padding-bottom--60">
    <div>
        <div>
            <a id="technologies"></a>
            <h4 class="center-align">The Team</h4>
        </div>
    </div>
    <div class="consultant list-across wrap">
        <div class="engineering">
            <img class="" src="https://v0001.jpg" alt="Person 1"/>
            <p>Person 1<br>Founder, Chairman &amp; CTO</p>
        </div>
        <div class="engineering">
            <img class="" src="https://v0002.png" alt="Person 2"/></a>
            <p>Person 2<br>Founder, VP of Engineering</p>
        </div>
        <div class="product">
            <img class="" src="https://v0003.jpg" alt="Person 3"/></a>
            <p>Person 3<br>Product</p>
        </div>
        <div class="Human Resources &amp; Admin">
            <img class="" src="https://v0004.jpg" alt="Person 4"/></a>
            <p>Person 4<br>People &amp; Places</p>
        </div>
        <div class="alliances">
            <img class="" src="https://v0005.jpg" alt="Person 5"/></a>
            <p>Person 5<br>VP of Alliances</p>
        </div>

到目前为止,我的 people.rake 文件中的内容如下:

  staff_site = Nokogiri::HTML(open("https://www.website.com/company/team-all"))
  all_hands = staff_site.css("div.consultant").map(&:text).map(&:squish)

我在获取 alt="" 标签(人名)中的所有元素时遇到了一些麻烦,因为它嵌套在几个 div 下。

目前,使用div.consultant,它获取所有姓名+ Angular 色,即Person 1Founder, Chairman; CTO,而不仅仅是 alt= 中的人名。

我怎样才能简单地获取 alt 中的元素?

最佳答案

您想要的输出不明确且 HTML 已损坏。

从这里开始:

require 'nokogiri'

doc = Nokogiri::HTML('<html><body><div class="consultant"><img alt="foo"/><img alt="bar" /></div></body></html>')
doc.search('div.consultant img').map{ |img| img['alt'] } # => ["foo", "bar"]

css 的输出上使用 text 不是一个好主意。 css 返回一个 NodeSet。针对 NodeSet 的 text 导致所有文本被连接起来,这通常会导致文本内容困惑,迫使您弄清楚如何将它再次分开,这最终是可怕的代码:

doc = Nokogiri::HTML('<html><body><p>foo</p><p>bar</p></body></html>')
doc.search('p').text # => "foobar"

此行为记录在 NodeSet#text 中:

Get the inner text of all contained Node objects

相反,使用 text (又名 inner_textcontent)针对各个节点,生成该节点的确切文本,然后您可以根据需要加入:

Returns the content for this Node

doc.search('p').map(&:text) # => ["foo", "bar"]

另见“How to avoid joining all text from Nodes when scraping”。

关于html - 使用 Nokogiri CSS 方法获取 alt 标签内的所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39129327/

相关文章:

javascript - 如何防止 url 中显示空的 "get"变量?

html - 如何在不影响主导航的情况下设置 CSS 子导航的样式

CSS 选择器悬停不适用于列表中的列表

ruby-on-rails - 链接 Webrick 代理

ruby - 运行 "bundle install"将 Gemfile.lock 中的 "git://"更改为 "https://"

ruby - 如何在 jekyll 液体中进行 url 编码?

jquery - 创建与 CSS/HTML 相关的丰富动态单页 Django Web 应用程序的最佳方法

javascript - jquery - 将 JSON 和 HTML 从 AJAX 响应中分离出来

php - 不断扩展 Div 以适应 PHP/MySQL 内容

jQuery 用户界面 : Dialog button styling