Home > Software engineering >  Selenium Python: Click on element with explicit string works but not when string is replaced by vari
Selenium Python: Click on element with explicit string works but not when string is replaced by vari

Time:06-24

When using the explicit text it works and the found element is clicked on but not when I use the variable:

This is the div: <div unselectable="on" >68915969-LS</div>

This works:

result = driver.find_element(By.XPATH,"//div[contains(text(),'68915969-LS')]")
action = ActionChains(driver)
action.move_to_element(result).click().perform()

When I replace '68915969-LS' by a variable nothing happens (no error, found line is not clicked on):

doc_number = '68915969-LS'
result = driver.find_element(By.XPATH,"//div[contains(text(),doc_number)]")
action = ActionChains(driver)
action.move_to_element(result).click().perform()

Any idea why?

Cheers Daniel

CodePudding user response:

You're actually looking for "doc_number" as a string. You need to resolve your value and join it into your xpath string.

Try this:

driver.find_element(By.XPATH,"//div[contains(text(),'" doc_number "')]")

CodePudding user response:

driver.find_element(By.XPATH,f"//div[contains(text(),'{doc_number}')]")

If you want you can also f string and put your variable in.

  • Related