Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Opening several URLs in same tab one by one using Selenium Python

This is my script where a JSON file contains all the URLs to be opened. What this script does is, it opens a URL takes screenshot and closes it; then opens a new one and so on.

What if I want to keep using the same browser session for all these URLs. Like Go to site 1, take screen cap. Now go to site 2 in the same browser/tab. and close the session/browser only at the last URL.

import json
from selenium.webdriver import Chrome

with open('path to json file', encoding='utf-8') as s:
    data = json.loads(s.read())

for site in data['sites']:
    driver = Chrome('path to chrome driver')
    driver.get(data['sites'][site])
    driver.get_screenshot_as_file(site + '.png')
    driver.close()
like image 309
Firaun Avatar asked Jan 28 '23 15:01

Firaun


1 Answers

Its because you are closing the browser every time loop ends , you just need to keep driver.close() outside the loop.

import json
from selenium.webdriver import Chrome

with open('path to json file', encoding='utf-8') as s:
    data = json.loads(s.read())

for site in data['sites']:
    driver = Chrome('path to chrome driver')
    driver.get(data['sites'][site])
    driver.get_screenshot_as_file(site + '.png')
driver.close()
like image 94
Pradeep hebbar Avatar answered Feb 19 '23 05:02

Pradeep hebbar