【问题标题】:Using Nokogiri's CSS method to get all elements within an alt tag使用 Nokogiri CSS 方法获取 alt 标签内的所有元素
【发布时间】:2017-04-25 02:19:05
【问题描述】:

我正在尝试使用 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,它获取所有名称+角色,即Person 1Founder, Chairman; CTO,而不仅仅是alt=中的人名。

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

【问题讨论】:

  • 请阅读“minimal reproducible example”。您的 HTML 无效;请确保结束标签位于正确的位置。没有这些 Nokogiri 会将它们放在它认为应该在的地方,这可能与您的想法大不相同。您的预期输出是什么?

标签: html css ruby nokogiri


【解决方案1】:

您想要的输出不清晰,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。 text 针对 NodeSet 会导致所有文本被连接起来,这通常会导致文本内容受损,迫使您弄清楚如何再次将其分开,这最终是可怕的代码:

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

此行为记录在NodeSet#text

获取所有包含的 Node 对象的内部文本

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

返回此节点的内容

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

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

【讨论】:

    猜你喜欢
    • 2020-02-01
    • 2015-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-06
    • 2016-07-06
    • 2012-10-01
    • 1970-01-01
    相关资源
    最近更新 更多