【发布时间】:2023-03-03 12:19:01
【问题描述】:
我一直在研究 Nokogiri 源代码,但不知道 Nokogiri 如何将字符串解析为 Elements。源代码可以在这里找到:
https://github.com/sparklemotion/nokogiri/tree/master/lib/nokogiri
例如:我有一个字符串:
raw = "<html> <body> body <div>this is div </div> </body> <html>"
Nokogiri::HTML(raw)
=>
#(Document:0x4d0c786 {
name = "document",
children = [
#(DTD:0x4d0bc6e { name = "html" }),
#(Element:0x4cfa46e {
name = "html",
children = [
#(Element:0x4cf9bfe {
name = "body",
children = [
#(Text "body"),
#(Element:0x4cf9348 {
name = "div",
children = [ #(Text "this is div")]
})]
})]
})]
})
我查看了nokogiri / lib / nokogiri / xml / sax,我看不到它如何解释 html 字符串。当我尝试阅读源代码时,我意识到在上面的输出中,有数据类型Element,但我在源代码中没有看到声明class Element 的任何地方。
一般来说,谁能帮我解释一下 Nokogiri 如何将字符串解析为上面的数据结构?
【问题讨论】:
-
Nokogiri 使用 libxml2,一个原生 C 库。实际上是 libxml2 进行解析。
-
谢谢。你知道 ruby 是如何与 libxml2 交互的吗?
-
你可能需要看看 C 的东西 (github.com/sparklemotion/nokogiri/tree/master/ext/nokogiri)
-
您在stackoverflow.com/questions/13791789/… 中提出了一个非常相似的问题。为什么选择的答案没有帮助?它是如何工作的超出了 Stack Overflow 的范围。
-
该问题询问是否存在将 HTML 解析为 DOM 的任何工具。 ,在这里我想更深入地了解它是如何工作的:-)。
标签: html ruby html-parsing nokogiri