适用于Python的javascript-aware html解析器〜

时间:2010-12-28 00:54:55

标签: javascript python lxml

<html>
<head>
    <script type="text/javascript">
    document.write('<a href="http://www.google.com">f*** js</a>');
    document.write("f*** js!");
    </script>
</head>
<body>
    <script type="text/javascript">
    document.write('<a href="http://www.google.com">f*** js</a>');
    document.write("f*** js!");
    </script>
<div><a href="http://www.google.com">f*** js</a></div>
</body>
</html>

我想使用xpath捕获上面html页面中的所有标签对象...

In [1]: import lxml.html as H

In [2]: f = open("test.html","r")

In [3]: c = f.read()

In [4]: doc = H.document_fromstring(c)

In [5]: doc.xpath('//a')
Out[5]: [<Element a at a01d17c>]

In [6]: a = doc.xpath('//a')[0]

In [7]: a.getparent()
Out[7]: <Element div at a01d41c>

我只能通过js~生成一个 但firefox xpath检查器可以找到所有标签!?

  
    
      

http://i.stack.imgur.com/0hSug.png

    
  

怎么做? THX〜!

<html>
<head>
</head>
<body>
<script language="javascript">
function over(){
a.innerHTML="mouse me"
}
function out(){
a.innerHTML="<a href='http://www.google.com'>google</a>"
}
</script>
<body><li id="a"onmouseover="over()" onmouseout="out()">mouse me</li>
</body>
</html>

3 个答案:

答案 0 :(得分:1)

不是python中关于javascript感知解析器的线索,但您可以使用ANTLR来完成这项工作。这个想法不是我的,所以我要离开link

它实际上非常酷,因为您可以优化解析器以选择性地选择需要解析(并执行)的指令。

答案 1 :(得分:0)

在Java中有Cobra。我不知道任何支持Javascript的HTML解析器。

答案 2 :(得分:0)

搜索谷歌搜索“javascript独立运行时”,我发现jslibs:一个“使用JavaScript作为通用脚本语言的独立JavaScript开发运行时环境”,基于“SpiderMonkey库” Gecko的JavaScript引擎“。

听起来很棒!我还没有测试,但似乎这将允许您运行您在页面中找到的JavaScript代码。我不知道它会变得多么棘手,但是......

相关问题