首页 > 解决方案 > 在 python (selenium.webdriver.firefox.webelement) 中查找 selenium 中的细分

问题描述

我使用 selenium 访问所有包含名册信息的 div:

# this returns a <selenium.webdriver.firefox.webelement.FirefoxWebElement
divs = driver.find_elements_by_class_name('appointment-template')

此元素内的这些 div 应如下所示:

div class="appointment-template" id="appointment-3500508">
<p class="title">Mentoruur</p>
<p class="time">11:15<span class="time-end"> - 12:15</span></p>
<ul class="facility">
    <li onclick=""
        title="HIC_Online">ONLINE
    </li>
</ul>
<ul class="docent">
    <li onclick=""
        title="HANSJE">HANSJE
    </li>
</ul>
<ul class="group">
    <li onclick=""
        title="ASD123">ASD123
    </li>
</ul>

我要做的下一件事是访问位于此 div 中的值,例如 docent 名称和时间值:

for div in divs:
  print(div.find_element_by_class_name('title'))
  print(div.find_element_by_class_name('time'))

这似乎不起作用:

selenium.common.exceptions.NoSuchElementException:消息:无法找到元素:.title

我如何使用 selenium 来获得如下值:
Mentoruur
11:15 - 12:15
Hansje

标签: pythonselenium

解决方案


为了在元素内定位元素,最好使用这种技术:

for div in divs:
  print(div.find_element_by_xpath('.//p[@class="title"]'))
  print(div.find_element_by_xpath('.//p[@class="time"]'))

.xpath 表达式前面的点表示“从这里开始”。这是我们在特定父元素中搜索时需要的


推荐阅读