Nokogiri: كيفية البحث عن عنصر معين، وإخراج اجتياز كامل؟ [مغلق

StackOverflow https://stackoverflow.com/questions/1484779

  •  18-09-2019
  •  | 
  •  

سؤال

باستخدام Nokogiri،

انا اريد ان اجد <p class="main"> Some text here...</p>

من مستند HTML،

ثم إخراج الموقع على النحو التالي أو شيء يظهر الشجرة

html > body > div class = "body" > p class= "main "
هل كانت مفيدة؟

المحلول

text="<html><body><div class='body'><p class='main'>some text here</p></div></body></html>"
doc = Nokogiri::HTML(text)
root = doc.root
node = doc.xpath('//p[@class="main"]').first
path = [node]
begin
  node = node.parent
  path.unshift node
end until node == root
path.map {|n| n.name}.join " > "

ممارسة لك لإضافة أي سمات تريدها.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top