【发布时间】:2015-12-17 03:16:19
【问题描述】:
我有一些 HTML 并希望获取 <body> 元素下的内容。但是,无论我尝试什么,在使用 Nokogiri 解析 HTML 之后,<doctype> 和 <head> 中的所有内容也都成为了 <body> 元素的一部分,当我检索 <body> 元素时,我看到了 @987654326 里面的东西@ 和 <meta> 和 <script> 标签也是。
我原来的 HTML 是:
<!DOCTYPE html \"about:legacy-compat\">
<html>
<head>
<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">
<title>Some Title</title>
<meta name='viewport' id='helloviewport' content='initial-scale=1.0,maximum-scale=2.5' />
<link rel='stylesheet' id='hello-stylesheet' type='text/css' href='some-4ac294cd125e1a062562aca1c83714ff.css'/>
<script id='hello-javascript' type='text/javascript' src='/hello/hello.js'></script>
</head>
<body marginwidth=\"6\" marginheight=\"6\" leftmargin=\"6\" topmargin=\"6\">
<div class=\"hello-status\">Hello World</div>
<div valign=\"top\"></div>
</body>
</html>
我使用的解决方案是:
parsed_html = Nokogiri::HTML(my_html)
body_tag_content = parsed_html.at('body')
puts body_tag_content.inner_html
我得到了什么:
<p>about:legacy-compat\"></p>
\n
<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">
\n
<title>Some title</title>
\n
<meta name='viewport' id='helloviewport' content='initial-scale=1.0,maximum-scale=2.5' />
\n
<link rel='stylesheet' id='hello-stylesheet' type='text/css' href='some-4ac294cd125e1a062562aca1c83714ff.css'/>
\n<script id='hello-javascript' type='text/javascript' src='/hello/hello.js'></script>
<div class=\"hello-status\">Hello World</div>
\n
<div valign=\"top\">\n\n</div>
我期待什么:
<div class=\"hello-status\">Hello World</div>
\n
<div valign=\"top\">\n\n</div>
知道这里发生了什么吗?
【问题讨论】: