Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open and close a website using default browser with python

I'm trying to write a python script on windows platform to open a webpage(such as Google), and then, after 10 seconds, close this website.

Note: I'm using Windows 7, Python 2.7.10, and IE

like image 543
Freeman Avatar asked Nov 27 '15 09:11

Freeman


People also ask

How do I open a website in a specific browser using Python?

To open a page in a specific browser, use the webbrowser. get() function to specify a particular browser.

How do you close a website in Python?

It is functional for all browsers, works on all major OS and its scripts are written in various languages i.e Python, Java, C#, etc, we will be working with Python. The close() method is a web driver command which closes the browser window.

How does Python code open a website?

Use webbrowser. open() to open a website open(url, new=1) to open the url in the default web browser of the system. new=1 opens a new browser window, new=0 opens in the same browser window, and new=2 opens in a new tab.

How do I open and close a web browser?

Click on the "X" button in the upper-right corner of the browser window to close it. You can also click "File" in the upper-left corner and then choose "Exit" to close the browser. For an alternate method, push "Alt" and "F4" simultaneously to close the browser using a Windows shortcut.


1 Answers

You can use pythons built in webbrowser module to open the default browser:

import webbrowser
webbrowser.open("http://google.co.uk")

https://docs.python.org/2/library/webbrowser.html


If you want more control of the browser (for example the ability to close the browser) you could investigate the use of Selenium, however I believe you have to be specific about what browser to open.

from selenium import webdriver
from time import sleep

driver = webdriver.Firefox()
driver.get("http://google.co.uk")
sleep(10)
driver.close()

http://selenium-python.readthedocs.org/en/latest/getting-started.html

like image 134
Panda Avatar answered Nov 11 '22 20:11

Panda