正确分隔数组中的字符串元素

Properly separate String elements in an Array

我正在尝试使用 Nokogiri 解析 HTML 页面以获取一些公司名称。

names = []
names << Nokogiri::HTML(mypage).css(".name a").text

我的结果是:

["MikeGetsLeadsUruBlondeLaunch LIVERynoRyderBoyer ProductionsStrangerxCerealLume CubeKatapyMacaulay Outdoor PromotionsFlixit ABMedia MosaicLiftCast.TVcool.mediaPeekKLIKseeStreamingo SolutionsPvgnaalughaUser"]

但我想得到的是:

["MikeGetsLeads", "Uru", "Blonde", "Launch LIVE", RynoRyderBoyer Productions", "Stranger", "xCereal", "Lume Cube", "Katapy", "Macaulay Outdoor Promotions", "Flixit AB", "Media Mosaic", "LiftCast.TV", "cool.media", "Peek", "KLIKsee", "Streamingo Solutions", "Pvgna", "alugha", "User"]

我尝试使用 .split 但它也没有给我正确的结果。在此页面上,每个名称都属于一个 <div>,因此在 HTML 结构中明确分开。

HTML 结构如下所示

<div class='name'>
<a href="https://angel.co/mikegetsleads-2" class="startup-link" data-id="1217822" data-type="Startup">MikeGetsLeads</a>
</div>
require 'rubygems'
require 'nokogiri'
require 'pp'

names = []
mypage = File.open("myhtml.html", "r")
Nokogiri::HTML(mypage).css(".name a").each do |item|
 names << item.text
end

pp names

returns:

["MikeGetsLeads", "MikeGetsLeads2", "MikeGetsLeads3"]

问题是,您将 text 与节点集一起使用,而不是与单个节点一起使用。使用 NodeSet,所有文本都连接成一个字符串。根据 NodeSet.inner_text 又名 text documentation:

Get the inner text of all contained Node objects

实际代码是:

def inner_text
  collect(&:inner_text).join('')
end

Node.content 又名 textinner_text

Returns the content for this Node

对此进行冥想:

require 'nokogiri'

doc = Nokogiri::HTML(<<EOT)
<div>
  <p>foo</p>
  <p>bar</p>
</div>
EOT

doc.css('p').class # => Nokogiri::XML::NodeSet
doc.css('p').text # => "foobar"

相反,您需要在单个节点上使用 text

doc.css('p').map{ |n| n.class } # => [Nokogiri::XML::Element, Nokogiri::XML::Element]
doc.css('p').map{ |n| n.text } # => ["foo", "bar"]

上一行可以简化为:

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

另见“”。