问题
I have a bit of code that finds an element based on visible text.
# Defines the text I am looking for
productName = "customer x job"
#Finds the element I am looking for
inputElement = driver.find_element_by_xpath(".//*[@id='demo_top']/div/table[2]/tbody/tr/td[1]/ul/li[2]/ul/li[1]/a".format(productName))
I need to click a box just to the right of this.
The specific xpath of the element is:
#What I just found
/html/body/div[1]/div/div/table[2]/tbody/tr/td[1]/ul/li[2]/ul/li[1]/a
#The box I actually want to click
/html/body/div[1]/div/div/table[2]/tbody/tr/td[1]/ul/li[2]/ul/li[1]/span/a
So I just need to add "/span/a" to the xpath of inputElement. The issue is, I don't know the specific xpath of this element. Is there a way for me to convert inputElement to a specific xpath, so I can just append "/span/a" to the end of it and click that element?
Edit: seems I was mistaken, I need to replace the final "a" with "span/a"
Below is the html:
<li class="TCbullet">
<span>
<a class="editCategory " onclick="return hs.htmlExpand(this, { objectType: 'iframe' } );" href="cat-frame-category.php?categoryID=1340"> </a> #I want to click this
<span class="sort">sort: 0</span>
</span>
<a class="anchorCategory" alt="Eden Cognitive Content" href="?ownerID=C518&g=1085&t=1340">Eden Cognitive Content</a> # I have found this
</li>
I want to access the editCatagory link, and I have found the anchorCategory link.
回答1:
You can call find_element_by_xpath() on the element you have already found:
link = inputElement.find_element_by_xpath('./preceding-sibling::span/a')
This would select the a
tag inside the span
that is following the a
tag you have found.
来源:https://stackoverflow.com/questions/24458860/webdriver-how-to-retrieve-the-xpath-of-found-element