如何找到锚标签的元素部分

How to find the element part of the anchor tag

我对硒完全陌生。请为提出愚蠢或愚蠢的问题而道歉。

我在网站上有以下内容。我感兴趣的是如何使用 selenium + python 获得 data-selectdate 值。获得 data-selectdate 值后,我想将其与我感兴趣的日期进行比较。

非常感谢您的帮助。

注意:我没有用Beautiful soup什么的。

干杯

<table role="grid" tabindex="0" summary="October 2018">
  <thead>
    <tr>
      <th role="columnheader" id="dayMonday"><abbr title="Monday">Mon</abbr></th>
      <th role="columnheader" id="dayTuesday"><abbr title="Tuesday">Tue</abbr></th>
      <th role="columnheader" id="dayWednesday"><abbr title="Wednesday">Wed</abbr></th>
      <th role="columnheader" id="dayThursday"><abbr title="Thursday">Thur</abbr></th>
      <th role="columnheader" id="dayFriday"><abbr title="Friday">Fri</abbr></th>
      <th role="columnheader" id="daySaturday"><abbr title="Saturday">Sat</abbr></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td role="gridcell" headers="dayMonday">
        <a data-selectdate="2018-10-22T00:00:00+01:00" data-selected="false" id="day22" 
          class="day-appointments-available">22</a>
      </td>
      <td role="gridcell" headers="dayTuesday">
        <a data-selectdate="2018-10-23T00:00:00+01:00" data-selected="false" id="day23" 
          class="day-appointments-available">23</a>
      </td>
      <td role="gridcell" headers="dayWednesday">
        <a data-selectdate="2018-10-24T00:00:00+01:00" data-selected="false" id="day24" 
          class="day-appointments-available">24</a>
      </td>
      <td role="gridcell" headers="dayThursday">
        <a data-selectdate="2018-10-25T00:00:00+01:00" data-selected="false" id="day25" 
          class="day-appointments-available">25</a>
      </td>
      <td role="gridcell" headers="dayFriday">
        <a data-selectdate="2018-10-26T00:00:00+01:00" data-selected="false" id="day26" 
          class="day-appointments-available">26</a>
      </td>
      <td role="gridcell" headers="daySaturday">
        <a data-selectdate="2018-10-27T00:00:00+01:00" data-selected="false" id="day27" 
          class="day-appointments-available">27</a>
      </td>
    </tr>
  </tbody>
</table>

要获取 属性的值 data-selectdate 您可以使用以下解决方案:

elements = driver.find_elements_by_css_selector("table[summary='October 2018'] tbody td[role='gridcell'][headers^='day']>a")
for element in elements:
    print(element.get_attribute("data-selectdate"))

您可以使用 get_attribute api of element class 来读取元素的属性值。

css_locator = "table tr:nth-child(1) > td[headers='dayMonday'] > a"
ele = driver.find_element_by_css_selector(css_locator)
selectdate = ele.get_attribute('data-selectdate')