【问题标题】:Parse broken html page in python在python中解析损坏的html页面
【发布时间】:2012-12-11 20:25:24
【问题描述】:

我正在尝试解析一个损坏的 html 页面,该页面在花药注释中包含一个注释,并且所有著名的 htmlparsers(如 beautifulsoup、lxml 和 HTMLParser)都给出了语法错误。以下是代码。如何忽略损坏代码的部分并解析页面的其余部分?

<html xmlns="http://www.w3.org/1999/xhtml"><head>

<script language="JavaScript">
<!--
     function setTimeOffsetVars (Link) { 
   // code removed
 } 

<!-- Image Preloader - takes an array of images to preload --> 
    function warningCheck(e, warnMsg) {
   // code removed
}
-->
</script>

</head>

<body topmargin="0" leftmargin="0" rightmargin="0" bottommargin="0" marginwidth="0" marginheight="0">
<!-- lot of useful code -->
</body></html>

【问题讨论】:

    标签: python html-parsing beautifulsoup lxml


    【解决方案1】:

    如果您知道问题出在哪里,您可以进行预处理:首先使用正则表达式之类的原始方法去除有问题的内部注释,然后使用真正的解析器对其进行处理。

    【讨论】:

      【解决方案2】:

      我对这个 html 没有任何错误。我试过beautifulsoup4和lxml。

      from bs4 import BeautifulSoup
      soup = BeautifulSoup(s)
      print soup.prettify()
      
      
      <html xmlns="http://www.w3.org/1999/xhtml">
       <head>
        <script language="JavaScript">
         &lt;!--
           function setTimeOffsetVars (Link) { 
         // code removed
       } 
      
      &lt;!-- Image Preloader - takes an array of images to preload --&gt; 
          function warningCheck(e, warnMsg) {
         // code removed
      }
      --&gt;
        </script>
       </head>
       <body bottommargin="0" leftmargin="0" marginheight="0" marginwidth="0" rightmargin="0" topmargin="0">
        <!-- lot of useful code -->
       </body>
      </html>
      

      【讨论】:

        猜你喜欢
        • 2014-02-17
        • 1970-01-01
        • 1970-01-01
        • 2014-06-01
        • 1970-01-01
        • 2023-04-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多