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

时间:2018-09-21 12:42:54

标签: python-2.7 selenium selenium-webdriver webdriver getattribute

我对硒完全陌生。请为提出愚蠢或愚蠢的问题表示歉意。

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

我们非常感谢您的帮助。

注意:我不使用美丽汤或其他任何东西。

欢呼声

<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>

2 个答案:

答案 0 :(得分:2)

要获取属性 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"))

答案 1 :(得分:0)

您可以使用get_attribute类的element API来读取元素的属性值。

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')