简体   繁体   中英

Selenium with Python: how to click preceding element

I'm working with a calendar and the only element I can access (due to non-askii issues) is a button that says 'Today' at the top of it. Directly to the left is a left arrow that takes you back a month; similarly, directly to the right is a right arrow that takes you forward a month. The html looks like this:

<tr style="-moz-user-select: none;">
<td class="button nav" style="-moz-user-select: none;" colspan="1">
    «
</td>
<td class="button nav" style="-moz-user-select: none;" colspan="1">
    ‹
</td>
<td class="button nav" style="-moz-user-select: none;" colspan="3">
    Today
</td>
<td class="button nav" style="-moz-user-select: none;" colspan="1">
    ›
</td>
<td class="button nav" style="-moz-user-select: none;" colspan="1">
    »
</td>
</tr>

I can click the 'Today' button by using:

driver.find_element_by_xpath("//td[text()='Today']").click()

Also, I can click the right arrow using 'following':

driver.find_element_by_xpath("//td[text()='Today']/following::td").click()

However, I can not figure out how to click the left arrow (I believe with 'preceding'). This is what I'm trying and.. it says it is unable to find element with xpath == //...

driver.find_element_by_xpath("//td[text()='Today']/preceding::td").click()

Is there another command I'm supposed to be using in order to find the previous element/sibling?

If it matters, I'm using IE9 and Selenium 2.44.

Thanks.

Try the below xpaths:

1- For clicking on the "<" arrow :

//td[contains(text(),'Today')]/preceding-sibling::td[1]

Above xpath locates the first preceding "td" element to the "td" element that has innerHTML/text as "Today" .

2- For clicking on the "<<" arrow :

//td[contains(text(),'Today')]/preceding-sibling::td[2]

Above xpath locates the second preceding "td" element to the "td" element that has innerHTML/text as "Today" .

While it does not use 'preceding', nor look at a sibling, I figured out how to do it like so:

precedes = self.driver.find_elements_by_xpath("//td[text()='Today']/../td")
precedes[1].click()

It returns to the parent of the td containing 'today', and then finds the child td's and chooses the second one (index 1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM