首页 > 解决方案 > 如何使用 Selenium-Python 从日历中选择第二天

问题描述

无法使用 Selenium 在日历中选择明天的日期

我尝试使用 find_element_by_css_selector 和 find_element_by_xpath 但似乎没有任何效果。

import time
import datetime
from time import strftime
from selenium import webdriver
browser = webdriver.Chrome("C:\Program Files (x86)\Google\Chrome\Application\chromedriver_win32\chromedriver.exe")
browser.get('https://www.****.com')

browser.find_element_by_id("UserName").send_keys("***")
browser.find_element_by_id("password").send_keys("***")
browser.find_element_by_id("submit-sign-in").click()


browser.find_element_by_id("Information").click()
browser.find_element_by_id("Amenities").click()

browser.find_element_by_id("reserve").click()
browser.find_element_by_id("resv-date").click()

******#The code works fine until here**********

#Trying to pick tomorrows date from the calendar.
browser.find_element_by_css_selector("a.ui-state-default.ui-state-active").click()

Not getting an error message but it doesn't select the required date

我附上了下面的图片:

<td class="  ui-datepicker-today" data-handler="selectDay" data-event="click" data-month="4" data-year="2019"><a class="ui-state-default ui-state-highlight" href="#">17</a></td>
<a class="ui-state-default ui-state-highlight" href="#">17</a></td>
<td class=" ui-datepicker-week-end  ui-datepicker-current-day" data-handler="selectDay" data-event="click" data-month="4" data-year="2019"><a class="ui-state-default ui-state-active" href="#">18</a></td>
<a class="ui-state-default ui-state-active" href="#">18</a>

片段 日历日期选择器

标签: seleniumdatepickercalendar

解决方案


您必须使用下面的 css 来选择第二天。

td.ui-datepicker-current-day + td

代码:

browser.find_element_by_css_selector("td.ui-datepicker-current-day+td").click()

+相邻的兄弟组合子。如果您在当前示例td.ui-datepicker-current-day中考虑选择当前日期,即17,但我们想选择以下同级,因此 using+将选择同级,并且我们指定将相邻同级过滤为td.

如果您想在相同的情况下使用 xpath,那么您可以使用following-sibling并按标签名称过滤,td如下所示。

//td[contains(@class, 'ui-datepicker-current-day')]/following-sibling::td

简而言之+,在 css 中几乎等同于following-sibling在 xpath 中,这将有助于选择同级项。

有关上述方法,请参阅以下有关 CSS 和 Xpath 的链接。

CSS


推荐阅读