5

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()

2 Answers 2

6

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()
Sign up to request clarification or add additional context in comments.

Comments

2

Then don't open / close the browser for each link, do it once:

driver = Chrome('path to chrome driver')
for site in data['sites']:
    driver.get(data['sites'][site])
    driver.get_screenshot_as_file(site + '.png')
driver.close()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.