简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM