我正在嘗試使用 Nokogiri 來獲取頁面的完整 HTML,但所有文本都被洗掉了。
我試過這個:
require 'nokogiri'
x = "<html> <body> <div class='example'><span>Hello</span></div></body></html>"
y = Nokogiri::HTML.parse(x).xpath("//*[not(text())]").each { |a| a.children.remove }
puts y.to_s
這輸出:
<div class="example"></div>
我也試過在沒有這個children.remove部分的情況下運行它:
y = Nokogiri::HTML.parse(x).xpath("//*[not(text())]")
puts y.to_s
但后來我得到:
<div class="example"><span>Hello</span></div>
但我真正想要的是:
<html><body><div class='example'><span></span></div></body></html>
uj5u.com熱心網友回復:
注意:這是一種非常激進的方法。像<script>、<style>和等標簽<noscript>還有text()包含 CSS、HTML 和 JS 的子節點,根據您的用例,您可能不想過濾掉這些子節點。
如果您對決議后的檔案進行操作而不是捕獲迭代器的回傳值,您將能夠洗掉文本節點,然后回傳檔案:
require 'nokogiri'
html = "<html> <body> <div class='example'><span>Hello</span></div></body></html>"
# Parse HTML
doc = Nokogiri::HTML.parse(html)
puts doc.inner_html
# => "<html> <body> <div class=\"example\"><span>Hello</span></div>\n</body>\n</html>"
# Remove text nodes from parsed document
doc.xpath("//text()").each { |t| t.remove }
puts doc.inner_html
# => "<html><body><div class=\"example\"><span></span></div></body></html>"
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/338553.html
上一篇:如何比較兩個陣列并獲得唯一值
