Xpath error: no such element: unable to locate. Using sublime text editor with latest release chrome80 and its webdrivers

Xpath error: no such element: unable to locate. Using sublime text editor with latest release chrome80 and its webdrivers

我尝试了多种方法通过 XPath 查找元素,但无法做到。

代码:

select_date = driver.find_element_by_xpath("//href[@text()='3:00 PM' and @data-day_ident='2021-05-25']")

HTML:

<a href="/" class="res-timeslot-select" data-day_ident="2021-05-25" data-start_int="1621980000000" data-timeslot_id="608ef96a8c15190007f9b015">3:00 PM</a>

我去掉了标签样式,因为它指的是 link。

错误:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//href[@text()='3:00 PM' and @data-day_ident='2021-05-25']"}
  (Session info: chrome=90.0.4430.212)

您的 xpath 正在查找带有标签 href 的元素,该元素不存在。有问题的元素有标签 a。没有看到你的 HTML 的其余部分,我不能 100% 确定,但根据你发布的内容,这个 xpath 可能会起作用:

"//a[@text()='3:00 PM' and @data-day_ident='2021-05-25']"

编辑:如果您只是想从页面上出现的 options/links 中抓取 time/date,则以下方法应该有效:

elements = driver.find_elements_by_css_selector('a.res-timeslot-select')
for element in elements:
    print(element.text + ' on ' + element.get_attribute('data-day_indent'))

到 select 根据日期和时间使用 XPath 的时间段,您可以使用以下 XPath 到 select 5 月 23 日唯一可用的时间段:

driver.find_elementss_by_xpath('//a[@data-day_ident='2021-05-23']')

5月24日select0:00时间段可以使用这个:

//a[@data-day_ident='2021-05-24' and (text()='0:00')]

到 select 1:30 5 月 24 日的时间段使用此

//a[@data-day_ident='2021-05-24' and (text()='1:30')]

以此类推
我希望现在已经清楚如何根据日期和时间在那里选择任何其他时间段了。

您发布的定位器有两个问题。

//href[@text()='3:00 PM' and @data-day_ident='2021-05-25']
  ^ href is an attribute of an A tag, not an element
       ^ remove @
  1. 没有元素href。元素是A标签。
  2. @text() 应该是 text()@ 符号用于属性,但 text() 是一种方法。

所以,你的 XPath 应该是

//a[text()='3:00 PM' and @data-day_ident='2021-05-25']
  ^ A is the element

这一个的问题是当前没有插槽。目前唯一可用的插槽是 5/23 1:30PM、5/24 12:00AM 和 5/24 1:30AM。您的定位器正在寻找 5/25 3:00PM。如果你把它改成

//a[text()='1:30 PM' and @data-day_ident='2021-05-23']

它会起作用。