Home > database >  Make a variable work inside a square bracket while working with selenium
Make a variable work inside a square bracket while working with selenium

Time:04-17

I'm working scraping a page, and I can't remember how to do it for make a variable work inside a string who is working with selenium inside another variable

from selenium import webdriver
from selenium.webdriver.common.by import By

len_trs_table=6
for i in range(0,int(len_trs_table)):
        tr = driver.find_element(By.XPATH,'/html/body/div[5]/div[8]/div/div[2]/div/div[3]/fieldset/div/div[1]/div/div[3]/fieldset/div/div[6]/table/tbody/tr[{i}]')

CodePudding user response:

You Have to use f-string

from selenium import webdriver
from selenium.webdriver.common.by import By

len_trs_table=6
for i in range(0,int(len_trs_table)):
        tr = driver.find_element(By.XPATH,f'/html/body/div[5]/div[8]/div/div[2]/div/div[3]/fieldset/div/div[1]/div/div[3]/fieldset/div/div[6]/table/tbody/tr[{i}]')

As shown in Above code you have to just writ f before your str(xpath)

If my answer helps you accept my answer and also upvote

CodePudding user response:

len_trs_table is of type integer. So while passing passing it to the xpath for variable substitution you have to convert it into a string type using either of the following strategies:

  • Using f-string:

    len_trs_table=6
    for i in range(0,int(len_trs_table)):
        tr = driver.find_element(By.XPATH, f'/html/body/div[5]/div[8]/div/div[2]/div/div[3]/fieldset/div/div[1]/div/div[3]/fieldset/div/div[6]/table/tbody/tr[{str(i)}]')
    
  • Related