Given a web element reference, how do I "append" a string to it so that I can find its next sibling element?
element = driver.find_element_by_xpath(u'//*[@id="submenu1"]/a[2]')
siblingElement = element "/following-sibling::td"
CodePudding user response:
Store all the XPath in a variable:
main_element = "//*[@id="submenu1"]/a[2]"
element = driver.find_element(By.XPATH, main_element)
siblingElement = main_element "/following-sibling::td"
element2 = driver.find_element(By.XPATH, siblingElement)
CodePudding user response:
You can not insert WebElement
object / reference in XPath string because Xpath expression should be string as you mentioned yourself.
What you do can is to locate the other element based on the existing element.
For example, if you want to find the /following-sibling::td
based on existing element you can do it as following:
element = driver.find_element(By.XPATH, '//*[@id="submenu1"]/a[2]')
siblingElement = element.find_element(By.XPATH, './following-sibling::td')
Pay attention:
- In the second line I'm applying
find_element
method onelement
object, not ondriver
object. - The XPath expression is staring with a dot
.
there to notify that this relative XPath is related to the current node. find_element(By.XPATH,
is used now whilefind_element_by_xpath
is deprecated.