Home > Blockchain >  How to insert CSV value into Selenium XPATH string?
How to insert CSV value into Selenium XPATH string?

Time:03-27

I am trying to modify an XPATH click command based on a line value in a CSV. In the code below, I'd like to replace "34" with the csv value.

I have the CSV imported into selenium, how should I go about dynamically inserting the CSV variable into the "34" place?

companystateselect = web.find_element(By.XPATH,"/html/body/div[3]/div[2]/div/div/div/mat-option[34]/span")
    companystateselect.click()

CSV Code

with open('test.csv', 'r') as csv_file:

    csv_reader = csv.reader(csv_file)

    for line in csv_reader:

CODE THAT WORKS

companystateselect = web.find_element(By.XPATH,"/html/body/div[3]/div[2]/div/div/div/mat-option[{0}]/span".format(line[1]))
        companystateselect.click()

CodePudding user response:

There are several ways to insert variables into strings with Python.
You can use this:

variable = '34'
companystateselect = web.find_element(By.XPATH,"/html/body/div[3]/div[2]/div/div/div/mat-option[{0}]/span".format(variable))
companystateselect.click()

UPD
in case each line in your code is exactly the value you want to use with your XPath locator it can be used as folowing:

with open('test.csv', 'r') as csv_file:

    csv_reader = csv.reader(csv_file)

    for line in csv_reader:
        companystateselect = web.find_element(By.XPATH,"/html/body/div[3]/div[2]/div/div/div/mat-option[{0}]/span".format(line))
        companystateselect.click()
  • Related