Chanwoo Ahn
Chanwoo Ahn

Reputation: 334

Selenium: complex XPath example

I need to locate a node with XPath in Selenium code for automation. The problem is that the node needs to be selected does not contain the information for identification, but another node which is descendant of a parent node of the target node does.

<object>...</object>

<object>
    <div>Name</div>
    <target></target>
</object>

<object>...</object>

To simplify the situation it looks like above. There are multiple "object" nodes and only distinguished from each other by "Name". While we can't use parenthesis in XPath, how can I select that node with driver.find_element_by_xpath() method?

Upvotes: 2

Views: 432

Answers (2)

cody
cody

Reputation: 11157

If I'm understanding your question correctly, the following XPath expression may be what you're looking for:

//div[text()="Name"]/../target

This essentially targets a div with text content Name, steps up to its parent with .. and then selects children of node type target.

If the target node is not an immediate child of the parent, the following will look for target nodes that are descendants of the parent at any depth (note the only difference is there are now two slashes in front of target):

//div[text()="Name"]/..//target

Upvotes: 2

KunduK
KunduK

Reputation: 33384

If you want do generic function and want pass your parameter every time.Try this.

def fxpath(varstring):
    Xpathelement = "//div[text()='{}']/../target".format(varstring)
    driver.find_element_by_xpath(Xpathelement)

fxpath('Name')

Upvotes: 1

Related Questions