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

Selenium with Python: how to click preceding element

我正在使用日历,我唯一可以访问的元素(由于非 askii 问题)是一个按钮,上面写着 'Today'。直接在左边是一个向左的箭头,可以让你返回一个月;同样,直接在右边的是一个右箭头,可以让你前进一个月。 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>

我可以通过以下方式单击 'Today' 按钮:

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

此外,我可以使用 'following' 单击右箭头:

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

但是,我不知道如何单击左箭头(我相信 'preceding')。这就是我正在尝试的并且..它说它无法使用 xpath == //...

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

我是否应该使用另一个命令来找到之前的 element/sibling?

如果重要的话,我使用的是 IE9 和 Selenium 2.44。

谢谢。

虽然它不使用 'preceding',也不看兄弟姐妹,但我想出了如何做到这一点:

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

它returns到包含'today'的td的父级,然后找到子td的并选择第二个(索引1)

试试下面的 xpaths:

1- 对于 点击“<”箭头:

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

上面的 xpath 将第一个 前面的 "td" 元素定位到具有 innerHTML/text 作为 "Today" 的 "td" 元素。

2- 对于 点击“<<”箭头:

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

上面的 xpath 将 第二个 "td" 元素定位到具有 innerHTML/text 和 "Today" 的 "td" 元素。