我正在尝试使用 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 & 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 & Admin">
<img class="" src="https://v0004.jpg" alt="Person 4"/></a>
<p>Person 4<br>People & 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_text
或 content
)针对各个节点,生成该节点的确切文本,然后您可以根据需要加入:
Returns the content for this Node
doc.search('p').map(&:text) # => ["foo", "bar"]
关于html - 使用 Nokogiri CSS 方法获取 alt 标签内的所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39129327/