【问题标题】:Issue parsing HTML using Nokogiri使用 Nokogiri 解析 HTML 的问题
【发布时间】: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\"&gt;</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>

知道这里发生了什么吗?

【问题讨论】:

    标签: html ruby nokogiri


    【解决方案1】:

    我首先清理了原始 HTML,从而使您的示例正常工作。我从 Doctype 中删除了“about:legacy-compat”,这似乎让 Nokogiri 搞砸了:

    # clean up the junk in the doctype
    my_html.sub!("\"about:legacy-compat\"", "")
    
    # parse and get the body
    parsed_html = Nokogiri::HTML(my_html)
    body_tag_content = parsed_html.at('body')
    
    puts body_tag_content.inner_html
    # => "\n      <div class=\"hello-status\">Hello World</div>\n      <div valign=\"top\"></div>\n   "
    

    一般来说,当您解析可能脏的第三方数据(例如 HTML)时,您应该先将其清理干净,以免解析器阻塞并做出意外的事情。您可以通过 linter 或“整洁”工具运行 HTML 以尝试自动清理它。当所有其他方法都失败时,您必须按照上述方法手动清洁它。

    HTML tidy/cleaning in Ruby 1.9

    【讨论】:

    • 是的,我发现“about:legacy-compat”是问题所在,但不确定为什么 HTML 解析没有处理它。在解析之前将其删除。
    猜你喜欢
    • 2013-09-16
    • 1970-01-01
    • 2011-11-16
    • 2013-08-15
    • 1970-01-01
    • 1970-01-01
    • 2012-02-03
    • 2013-04-19
    • 1970-01-01
    相关资源
    最近更新 更多