简体   繁体   English

Selenium与Python:如何单击前面的元素

[英]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. 我正在使用日历,并且我可以访问的唯一元素(由于非askii问题)是在其顶部显示“今天”的按钮。 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: html看起来像这样:

<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 == //... 这就是我正在尝试的..它说它无法使用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. 如果有关系,我正在使用IE9和Selenium 2.44。

Thanks. 谢谢。

Try the below xpaths: 尝试以下xpath:

1- For clicking on the "<" arrow : 1-对于单击“ <”箭头

//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" . 在xpath上方将第一个前面的“ td”元素定位到具有innerHTML / text为“ Today”的“ td”元素

2- For clicking on the "<<" arrow : 2- 点击“ <<”箭头

//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" . 在xpath上方将第二个前面的“ td”元素定位到具有innerHTML / text为“ Today”的“ td”元素

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) 它返回到包含“ today”的td的父代,然后找到子td并选择第二个(索引1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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