对于每个 运行 如何使用 f 字符串更改正在调用的项目

For every run how to change the item being called using f-strings

所以我试图在每次 for 循环运行时这样做,它会稍微改变 driver.get() 函数,所以我可以缩短我的代码而不是输入 driver1.get、driver2.get driver3.get

我尝试了一些东西,但都没有用:

from selenium import webdriver

driver1 = webdriver.Chrome()
driver2 = webdriver.Chrome()
driver3 = webdriver.Chrome()

drivers = ['driver1', 'driver2', 'driver3']

for i in range(1, 3):
    driver[f'{i}'].get('google.com')

出现类型错误:

'int' object is not subscriptable

driver1 = webdriver.Chrome()
driver2 = webdriver.Chrome()
driver3 = webdriver.Chrome()

drivers = ['driver1', 'driver2', 'driver3']

for driver in drivers:
    [f'{drivers}'].get('google.com')

给我一个 AttributeError:

'list' object has no attribute 'get'

我觉得这是一个简单的事情,但是我的Python基础书怎么修改都弄不明白

f-strings in Python是一种字符串格式化机制。

所以在行内,

driver[f'{i}'].get('google.com')

你需要将i的类型转换为字符串,如下所示:

driver[f'{str(i)}'].get('google.com')
drivers=[]
for i in range(3):
    driver = webdriver.Chrome()
    drivers.append(driver)

两种方式:

for i in range(3):
    drivers[i].get('https://www.google.com/')

for driver in drivers:
    driver.get('https://www.google.com/')

您可以这样做来制作 x 数量的驱动程序并访问它们。