[英]Is there a way to get the raw HTML from Nokogiri?
我已經看過“ 如何通過使用Ruby或Nokogiri獲取頁面的原始HTML源代碼? ”,它使用了類似這樣的內容:
file = open("index.html")
puts file.read
page = Nokogiri::HTML(file)
但這似乎將讀取點移動到文件的末尾,以使Nokogiri無法再讀取文件。 如果我調換了read
和Nokogiri的電話:
file = open("index.html")
puts file.read
page = Nokogiri::HTML(file)
該文件不再輸出。 我希望能夠查詢Nokogiri最初使用的HTML,以便可以在原始源代碼上進行自己的額外解析。 理想情況下,我想要類似
file = open("index.html")
page = Nokogiri::HTML(file)
raw_html = page.html
注意:我也嘗試過page.to_html
,但是似乎稍微改變了格式。
通常,您傳遞一個File
實例,以便可以通過塊對其進行處理,但是傳遞一個字符串也可以 :
html = File.read("index.html")
page = Nokogiri::HTML(html)
page_html = page.html
僅供參考:您還可以要求Nokogiri在解析Nokogiri或進行修改后,返回文檔的HTML(或XML,如果您使用的是XML)。
doc = Nokogiri::HTML('<head><body>foo</body></head>')
puts doc.to_html
它將以pry輸出:
[4] (pry) main: 0> puts doc.to_html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></head>
<body>foo</body>
</html>
請注意,Nokogiri進行了一些修復,以使HTML“更好”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.