1

こんにちは、私は以下のコードとしてhtmlコードを持っています。テキストを中に入れたい<a>(.*)</a>

私はこの結果を得たい:

data 1 : hello1
data 2 : hello2
data 3 : hello3

その入力から:

<a>
hello1
</a>
<a>
hello2
</a>
<a>
hello3
</a>
4

1 に答える 1

2

2 つのコメントを拡張すると、次の Nokogiri コードがこの例で機能します。xpath または CSS のいずれかを使用できます。専用のパーサーは、独自の正規表現をローリングするよりもはるかに強力です。

> require 'nokogiri'
 => true 
> doc = Nokogiri::HTML("<a>hello1</a><a>hello2</a><a>hello3</a>")
 => #<Nokogiri::HTML::Document:0x3ffec2494f48 name="document" children=[#<Nokogiri::XML::DTD:0x3ffec2494bd8 name="html">, #<Nokogiri::XML::Element:0x3ffec2494458 name="html" children=[#<Nokogiri::XML::Element:0x3ffec2494250 name="body" children=[#<Nokogiri::XML::Element:0x3ffec2494048 name="a" children=[#<Nokogiri::XML::Text:0x3ffec2493e40 "hello1">]>, #<Nokogiri::XML::Element:0x3ffec249dc88 name="a" children=[#<Nokogiri::XML::Text:0x3ffec249da80 "hello2">]>, #<Nokogiri::XML::Element:0x3ffec249d878 name="a" children=[#<Nokogiri::XML::Text:0x3ffec249d670 "hello3">]>]>]>]> 
> doc.css('a').each { |node| p node.text }
"hello1"
"hello2"
"hello3"
 => 0 

更新: まだインストールしていない場合は、nokogiri gem が必要です。

sudo gem install nokogiri

設定によっては、先頭に追加する必要がある場合もあります

require 'rubygems'
于 2012-07-18T11:57:48.227 に答える