首页 > 解决方案 > Avoid opening an new browser for every instance in Selenium Python

问题描述

I got a Python Selenium project that does what I want (yay!) but for every instance it opens a new browser window. Is there any way to prevent that?

I've went through the documentation of Selenium but they refer to driver.get(url). It's most likely because it's in the for...loop but I can't seem to get the URL to change with the queries and params if it's outside of the for...loop.

So, for example, I want to open these URLs:

etc..

from selenium import webdriver
import time
from itertools import product

params = ['Parameter1', 'Parameter2', 'Parameter3', 'Parameter4']

queries = ['Query1', 'Query2', 'Query3', 'Query4',]

for (param, query) in product(params,queries):
    url = f'https://www.google.com/search?q=site%3A{param}+%22{query}%22' # google as an example
    driver = webdriver.Chrome('G:/Python Projects/venv/Lib/site-packages/chromedriver.exe')
    driver.get(url)

#does stuff

标签: pythonseleniumfor-loopselenium-webdriverselenium-chromedriver

解决方案


You are declaring your path to Chrome in the loop. Declare it once and reuse:

from itertools import product
from selenium import webdriver

params = ['Parameter1', 'Parameter2', 'Parameter3', 'Parameter4']

queries = ['Query1', 'Query2', 'Query3', 'Query4',]
driver = webdriver.Chrome(executable_path='/snap/bin/chromium.chromedriver')

for (param, query) in product(params,queries):
    url = f'https://www.google.com/search?q=site%3A{param}+%22{query}%22'
    driver.get(url)
# driver.close()

推荐阅读