How to open a URL in Python

In this tutorial, we are going to learn how to open a URL in Python.

Here we use the Python program to open the URL with the help of python libraries.

There are many methods to open the URL but here we discuss only two of them

  1. Using webbrowser Python library

  2. Using selenium Python library

1. Using the webbrowser  Python library

webbrowser is a python library and with the help of this library we can easily access a web browser using some of its inbuilt functions like “open_new_tab”.

let’s start coding:

  • 1st we have to install webbrowser
pip install webbrowser
  • Then we have to import this library.
  • Now we want to open google so we will create a Google URL(‘https://www.google.com’).
  • Now using the inbuilt function “open_new_tab” of webbrowser and passing the URL as a parameter we can able to open the web page.
import webbrowser  
url= 'https://www.google.com' 
webbrowser.open_new_tab(url)

output:

True

How to open a URL in Python

 

2. Using the selenium Python library

Selenium is also a Python library and this will also help us to open URL links and to browse web browsers using python script.

let’s start coding:

  • 1st we have to install the Nselenium library
pip install selenium
  • Now we will import webdriver from the selenium library
from selenium import webdriver

 

WebDriver is an inbuilt function of selenium that help us to interact with the web browser present in our system. So for this, we have to download WebDriver. You can download this from the links given below.

Chrome:https://sites.google.com/a/chromium.org/chromedriver/downloads

Firefox:https://github.com/mozilla/geckodriver/releases

  • Now check where your  WebDriver is downloaded and copy that path
  • Providing the path of the Chrome Web driver we can easily set our chrome browser/driver
  • At last with the help of the “.get()” function, we can easily open our URL
from selenium import webdriver 
path='C:\\Users\\sumit\\.wdm\\drivers\\chromedriver\\win32\\102.0.5005.61\\chromedriver.exe'
driver = webdriver.Chrome(path) 
url="https://www.google.com"
driver.get(url)

output:

<ipython-input-25-a6ed5007a94c>:4: DeprecationWarning: executable_path has been deprecated, please pass in a Service object
  driver = webdriver.Chrome(path)

How to open a URL in Python

Thus, we have learned how to open a URL in Python.

Leave a Reply

Your email address will not be published.