在Python程序中嵌入Web浏览器

7
如何在Python程序中嵌入Web浏览器?它需要在Linux上运行(GTK,Qt都可以),或者跨平台。我已经看过了嵌入pywebgtk和Qt的WebKit小部件。但是这些似乎只有渲染引擎。特别是,我想要支持后退/前进和选项卡式浏览。类似于这样的东西是否预打包好了,还是我必须自己实现?wxWebConnect似乎大致符合我的想法,但它没有Python绑定。

请查看 https://kmandla.wordpress.com/2010/05/24/the-1-2kb-python-browser-script/ 及其评论;阅读 http://wiki.python.org/moin/WebBrowserProgramming,特别是有关“Python包装Web 'Libraries'和浏览器技术”的部分。 - agf
1
我的第一反应是,你要么正在开发一个 Web 应用程序并使用浏览器,要么不使用浏览器。混合解决方案似乎有点棘手。 - Steven Rumbalski
@agf:如果我理解正确,这两个链接只涉及嵌入一个WebKit渲染器,而我已经知道如何做了,而不是一个实际的浏览器。 - Mechanical snail
1
@机械蜗牛 - 根据你对agf的最后回复,听起来你正在尝试让浏览器和服务器应用程序一起启动和停止。为什么不编写一个小应用程序来启动它们两个,监视它们,并在其中一个终止时停止? - Andrew Edgecombe
@jdigital:我考虑过了,但我不知道该怎么做。firefox 立即返回,所以你无法知道用户何时退出浏览器。chromium-browser 似乎不支持单独的配置文件(即使你指定 --user-data-dir=/tmp/somedir,默认配置文件中保存的密码仍然会出现!) - Mechanical snail
显示剩余5条评论
1个回答

4

http://pypi.python.org/pypi/selenium/2.7.0

您可以安装Selenium软件包,并在同一台机器上运行一个服务器(只是不同的进程),然后通过您的Python代码连接到它:

java -jar selenium-server-standalone-2.7.0.jar

接下来:

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys
import time

browser = webdriver.Firefox() # Get local session of firefox
browser.get("http://www.yahoo.com") # Load page
assert "Yahoo!" in browser.title
elem = browser.find_element_by_name("p") # Find the query box
elem.send_keys("seleniumhq" + Keys.RETURN)
time.sleep(0.2) # Let the page load, will be added to the API
try:
    browser.find_element_by_xpath("//a[contains(@href,'http://seleniumhq.org')]")
except NoSuchElementException:
    assert 0, "can't find seleniumhq"
browser.close()

您可以使用subprocess在Python代码中启动服务器。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接