Nokogiri كيفية الحصول على النص الأصل وليس نص الطفل والرجوع إلى النص مرة أخرى إلى الوالدين
سؤال
دعنا نقول أن لدي هذه العينة:
page = "<html><body><h1 class='foo'></h1><p class='foo'>hello people<a href='http://'>hello world</a></p></body></html>"
@nodes = []
Nokogiri::HTML(page).traverse do |n|
if n[:class] == "foo"
@nodes << {:name => n.name, :xpath => n.path, :text => n.text }
end
end
النتائج من شأنها أن n.text
سيكون hello peoplehello world
, ، أريد أن أفعل ذلك بطريقة حتى أتمكن من الحصول على النص الأصل ونص الأطفال الخاص به، لكنهم يربطونهم بعلاماتهم
لذلك ستكون النتيجة شيء مثل
@nodes[0][:text]=""
@node[1][:text]= [{:Elementtext1 => "hello people", :ElementObject1 => elementObject},{:Elementtext2 => "hello world", :ElementObject2 => elementObject}]
المحلول
هناك نذهب
require 'rubygems'
require 'nokogiri'
doc = Nokogiri::HTML(DATA.read)
nodes = doc.root.css('.foo').collect do |n|
{ :name => n.name,
:xpath => n.path,
:text => n.xpath('.//text()').collect{|t|
{ :parent => t.parent.name,
:text => t.text }}}
end
p nodes
__END__
<html>
<body>
<h1 class='foo'></h1>
<p class='foo'>hello people<a href='http://'>hello world</a></p>
</body>
</html>
لا يمكنك الوصول إلى جميع العناصر باستخدام traverse
لأنه يزور فقط الأطفال المباشرين من الجذر. وبالتالي، استخدم محدد CSS للحصول على جميع العناصر مع الفصل foo
. وبعد ثم، لكل عنصر تم العثور عليه، يمكنني استخدام محدد XPath للحصول على جميع العقد النصية أدناه.
لا تنتمي إلى StackOverflow