如何解析包含javascript代码的html

时间:2011-08-15 10:53:44

标签: javascript python html

如何解析大量使用javascript的html文档?我知道python中有一些库可以解析静态xml / html文件,我基本上是在寻找一个程序或库(甚至是firefox插件),它读取html + javascript,执行javascript位并输出html代码而不用javascript所以如果在浏览器中显示它会看起来相同。

作为一个简单的例子

<a href="javascript:web_link(34, true);">link</a>
应该用javascript函数返回的适当值替换

,例如

<a href="http://www.example.com">link</a>

一个更复杂的例子是一个保存的facebook html页面,里面堆满了大量的javascript代码。

可能与...有关 How to "execute" HTML+Javascript page with Node.js 但我真的需要Node.js和JSDOM吗?也略有关系 Python library for rendering HTML and javascript 但我对渲染纯html输出并不感兴趣。

3 个答案:

答案 0 :(得分:3)

您可以将Selenium与python一起用作详细的here

示例:

import xmlrpclib

# Make an object to represent the XML-RPC server.
server_url = "http://localhost:8080/selenium-driver/RPC2"
app = xmlrpclib.ServerProxy(server_url)

# Bump timeout a little higher than the default 5 seconds
app.setTimeout(15)

import os
os.system('start run_firefox.bat')

print app.open('http://localhost:8080/AUT/000000A/http/www.amazon.com/')
print app.verifyTitle('Amazon.com: Welcome')
print app.verifySelected('url', 'All Products')
print app.select('url', 'Books')
print app.verifySelected('url', 'Books')
print app.verifyValue('field-keywords', '')
print app.type('field-keywords', 'Python Cookbook')
print app.clickAndWait('Go')
print app.verifyTitle('Amazon.com: Books Search Results: Python Cookbook')
print app.verifyTextPresent('Python Cookbook', '')
print app.verifyTextPresent('Alex Martellibot, David Ascher', '')
print app.testComplete()

答案 1 :(得分:2)

来自Mozilla Gecko FAQ

  

Q值。你能从Unix shell脚本调用Gecko引擎吗?你能发送HTML并找回可能发送给打印机的网页吗?

     

一个。不是真的支持;但是,您可以通过使用Gecko的嵌入API编写自己的应用程序来获得您想要的东西。请注意,目前无法在屏幕上没有窗口小部件的情况下进行打印以进行渲染。

输出你想要的东西的程序中的

Embedding Gecko可能太沉重,但至少你的输出会一样好。

答案 2 :(得分:0)

可以使用PhantomJS

加载

Selenium

$ ipython

In [1]: from selenium import webdriver

In [2]: browser=webdriver.PhantomJS()

In [3]: browser.get('http://seleniumhq.org/')

In [4]: browser.title
Out[4]: u'Selenium - Web Browser Automation'