Monday, November 6, 2017

How to Open Multiple URL In Selenium Automation Using Python


Today we are going to show you, how we can open multiple URL from CSV file using Python. First we have to create new python file. After creating the python file we need to import following libraries in python
 
import csv
from selenium import webdriver
 



Now,  We have to create main function to for CSV url reader.

if __name__ == "__main__":
    with open("URL.csv") as url_obj:
        csv_url_reader(url_obj)
 
The structure of CSV file is as below, we can give our own type here.

SN,Site Name,URL
1,Amazon,https://amazon.com
2,Yahoo,https://yahoo.com
3,Google,https://google.com
SN
Site Name
URL
1
Amazon
https://amazon.com
2
Yahoo
https://yahoo.com
3
Google
https://google.com

 
Then, we can read CSV file using csv_url_reader function as below function
def csv_url_reader(url_obj):
    reader = csv.DictReader(url_obj, delimiter=',')
    for line in reader:
        print(line["SN"],line["Site Name"],line["URL"]),
        URL = line["URL"]
        site = line["Site Name"]
        chromedriver = "D:\Automation\Python\chromedriver"        driver = webdriver.Chrome(chromedriver)
        driver.get(URL)
        try:
            assert site in driver.title
        except AssertionError:
            print("Title don't match")
        else:
            print("Title Matched")
        driver.quit()

Here, we are reading csv line by line and driver.get(URL) is opening each URL from CSV file in the loop. The chrome driver location may varies as it is the location of chromedriver we have kept in our machine. The assert function is performing assertion test with the Site name and Title matched will be shown if assert pass.

Complete Code:
import csv
from selenium import webdriver
def csv_url_reader(url_obj):
    reader = csv.DictReader(url_obj, delimiter=',')
    for line in reader:
        print(line["SN"],line["Site Name"],line["URL"]),
        URL = line["URL"]
        site = line["Site Name"]
        chromedriver = "D:\Automation\Python\chromedriver"        driver = webdriver.Chrome(chromedriver)
        driver.get(URL)
        try:
            assert site in driver.title
        except AssertionError:
            print("Title don't match")
        else:
            print("Title Matched")
        driver.quit()
# ----------------------------------------------------------------------if __name__ == "__main__":
    with open("URL.csv") as url_obj:
        csv_url_reader(url_obj)

2 comments:

  1. Just right click on the link and hold it to drag a box around the links. When you release the right click of your mouse, all those links will open in new tabs.

    For more Details visit https://wbmsmart.com/

    ReplyDelete
  2. Looking for smart home devices? Welcome to the smart home Devices, where you'll find great prices on a variety of smart products to automate your Smart Home.
    For more detail: https://wbmsmart.com/

    ReplyDelete