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

Time:04-19

So I'm trying to make so everytime the for loop runs, it changes slightly the driver.get() function, so i can shorten my code instead of typing driver1.get, driver2.get driver3.get

I tried to things and neither work:

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

Gets a TypeError:

'int' object is not subscriptable

and

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

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

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

gives me an AttributeError:

'list' object has no attribute 'get'

I feel like this is a simple matter, but I cant get it straight no matter how much I revise my Python Basics book.

CodePudding user response:

f-strings in Python is a string formatting mechanism.

So within the line,

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

you need to convert the type of i as string while passing as follows:

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

CodePudding user response:

drivers=[]
for i in range(3):
    driver = webdriver.Chrome()
    drivers.append(driver)

Two ways:

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

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

You could just do that to make x amount of drivers and access them.

  • Related