7

How can I embed a web browser in a Python program? It needs to run on Linux (GTK, Qt are fine), or cross-platform.

I have looked at embedding pywebgtk and Qt's WebKit widget. But these seem to have little more than a rendering engine. In particular, I'd like support for back/forward and tabbed browsing. Is something like this pre-packaged, or do I have to implement it myself?

wxWebConnect seems to be roughly what I was thinking of, but it has no Python bindings.

10
  • See kmandla.wordpress.com/2010/05/24/… and the comments; read wiki.python.org/moin/WebBrowserProgramming especially the section on "Python Wrappers around Web "Libraries" and Browser Technology"
    – agf
    Sep 28, 2011 at 22:06
  • 1
    My knee-jerk response is that you are either developing a web application and you use a browser or you're not and you don't use a browser. A hybrid solution seems a bit sticky. Sep 28, 2011 at 22:07
  • @agf: If I'm reading those right, both links only deal with embedding a just a WebKit renderer, which I already know how to do, rather than an actual browser. Sep 28, 2011 at 22:18
  • I think the links in the comments to the blog post talk about actual minimal browsers built around webkit in Python.
    – agf
    Sep 28, 2011 at 22:21
  • 1
    @Mechanical snail - given your last reply to agf, it sounds like you're trying to get a browser and a server app to start and stop together. Why not just write a small application to start them both, monitor them and stop when one is terminated? Sep 28, 2011 at 23:36

1 Answer 1

5

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

You can install the selenium package and run a server (same machine, just a different process) with it which you connect to with your python code:

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

then:

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()

You could use subprocess to start the server inside your python code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.