python - 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:
https://www.google.com/search?q=site%3AParameter1+%22Query1%22
https://www.google.com/search?q=site%3AParameter2+%22Query1%22
https://www.google.com/search?q=site%3AParameter3+%22Query1%22
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
解决方案
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()
推荐阅读
- python - Pandas 代码将大于 0.5 的值舍入为 1
- powershell - 加密 Excel 电子表格 epplus powershell
- amazon-s3 - 将数据从 TIBCO Businessworks 5 发送到 Amazon S3
- python - 用于提取文件路径(不是 url)的通用正则表达式
- azure - Logging in Azure WebApp
- c++ - constexpr 计算的编译时性能
- javascript - 以 this 作为 arg 的复选框开关不会保存更改的 .checked 值
- mysql - MySQL 与另一个条件搜索匹配
- google-cloud-dataflow - 数据流管道 - “处理卡在步骤中
至少对于 - aws-cdk - 如何将标签添加到 AWS-CDK 构造