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)