【问题标题】:Parsing xhtml with lxml python用lxml python解析xhtml
【发布时间】:2012-08-08 16:14:45
【问题描述】:

小问题,真的卡在这里了,不明白怎么回事,就是想从网上解析一个普通的xhtml,没什么特别的……

这是错误:

 File "class/page.py", line 85, in xslParse
    doc = lxml.etree.fromstring(self.content)
    File "lxml.etree.pyx", line 2753, in lxml.etree.fromstring (src/lxml/lxml.etree.c:54647)
    File "parser.pxi", line 1578, in lxml.etree._parseMemoryDocument (src/lxml/lxml.etree.c:82764)
    File "parser.pxi", line 1457, in lxml.etree._parseDoc (src/lxml/lxml.etree.c:81562)
    File "parser.pxi", line 965, in lxml.etree._BaseParser._parseDoc (src/lxml/lxml.etree.c:78232)
    File "parser.pxi", line 569, in lxml.etree._ParserContext._handleParseResultDoc (src/lxml/lxml.etree.c:74488)
    File "parser.pxi", line 650, in lxml.etree._handleParseResult (src/lxml/lxml.etree.c:75379)
    File "parser.pxi", line 590, in lxml.etree._raiseParseError (src/lxml/lxml.etree.c:74712)
    XMLSyntaxError: StartTag: invalid element name, line 1, column 2

self.content是一个http响应给出的普通字符串,没有clean,没有replace,什么都没有,只是服务器的响应,那么fu..是什么?

html的开头是:

<!doctype html>
<!-- paulirish.com/2008/conditional-stylesheets-vs-css-hacks-answer-neither/ -->
<!--[if lt IE 7 ]> <html lang="fr" class="no-js ie6" itemscope itemtype="http://schema.org/Product"> <![endif]-->
<!--[if IE 7 ]>    <html lang="fr" class="no-js ie7" itemscope itemtype="http://schema.org/Product"> <![endif]-->
<!--[if IE 8 ]>    <html lang="fr" class="no-js ie8" itemscope itemtype="http://schema.org/Product"> <![endif]-->
<!--[if IE 9 ]>    <html lang="fr" class="no-js ie9" itemscope itemtype="http://schema.org/Product"> <![endif]-->
<!--[if (gt IE 9)|!(IE)]><!--> <html lang="en" class="no-js" itemscope itemtype="http://schema.org/Product"> <!--<![endif]-->
<head>......

一个普通的网页,为什么lxml不能解析一个普通的格式良好的doc?

【问题讨论】:

  • 你试过用lxml.html.fromstring代替lxml.etree.fromstring吗?
  • 马上去看看!谢谢兄弟

标签: python lxml parsexml


【解决方案1】:

&lt;!doctype html&gt; 表示它是使用 HTML 语法的 HTML5 文档。因此,您应该使用 HTML(而不是 XML)解析器。为了比较,XML 文档可能以 &lt;?xml version="1.0" encoding="UTF-8"?&gt; 开头。

您可以将lxml.html.fromstring() 用作@unutbu suggested in the comments

如果您通过 HTTP 接收页面,则使用 XML 语法的 HTML5 文档应具有 XML 媒体类型,例如 application/xhtml+xmlapplication/xml,而不是例如用于 HTML 语法的 text/html

【讨论】:

  • 复制那个!现在事情很清楚了,以为 html doc 也是 xml doc ......那么发送 mime 类型 lik text/html 和 xml 有什么区别,浏览器,lxml 渲染两种类型相同吗?
  • HTML 和 XML 是不同的语言;不同的解析器用于解析它们返回具有相似但不同接口的不同对象。
猜你喜欢
  • 1970-01-01
  • 2012-06-10
  • 2016-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多