Home > Net >  Find element by xpath doesn't work when macro used, Selenium python
Find element by xpath doesn't work when macro used, Selenium python

Time:04-26

I'm running into an issue where when I try to use a macro into the xpath, it doesn't work and no errors pop up. It clicks an area that doesn't match with the xpath. I use the chrome webdriver.

My code:

dob = 'Apr 18, 1967'

driver.find_element_by_xpath("//span[contains(., dob)]").click()

It works when I don't use the macro

driver.find_element_by_xpath("//span[contains(., 'Apr 18, 1967')]").click()

This is the area I am trying to interact with:

<span >LastName, FirstName (Apr 18, 1967)</span>

This is what it interacts with when I use the macro in xpath:

<div id="sidePanelCollapseButton" >

I've tried locating with the class but the xpath for that would return several 10s of results, so going by the DOB is the easiest way to narrow it down.

CodePudding user response:

The code that you've been trying

driver.find_element_by_xpath("//span[contains(., dob)]").click()

is basically looking for a span tag that has dob as an innerText. Since dob is not actually present in HTML and it is a var type, you should use f-Strings, something like this:

dob = 'Apr 18, 1967'
driver.find_element_by_xpath(f"//span[contains(., {dob})]").click()
  • Related