【问题标题】:How to pair an element's children by CSS selector using Selenium WebDriver in Python?如何在 Python 中使用 Selenium WebDriver 通过 CSS 选择器配对元素的子元素?
【发布时间】:2023-03-24 15:18:01
【问题描述】:

我正在使用 Selenium WebDriver 从许多网页中抓取信息。我想知道是否可以通过 CSS 选择器选择多个子元素。 HTML 结构如下所示:

<section id="education">
  <div class="degree">
    <h3 class="school"> School1 </h3>
    <p class="year"> 2002-2008 </p>
  </div>
  <div class="degree">
    <h3 class="school"> School2 </h3>
  </div>
</section>

在这种情况下,我想选择具有相应年份范围的学校名称。但如果我只是使用:

driver.find_elements_by_css_selector('section[id="education"] div[class="school"]')
driver.find_elements_by_css_selector('section[id="education"] p[class="year"]')

我会得到两个列表:[School1, School2]['2002-2008'],我无法分辨出哪个学校对应于'2002-2008' 的年级。那么,是否可以将相应的学校名称和年份范围结合在一起呢?如果有其他方法可以绕过它,那也会有所帮助。

【问题讨论】:

    标签: python selenium css-selectors


    【解决方案1】:

    您必须循环遍历.degree 标记并从中成对提取所需信息。以下是正常的操作方法:

    education = driver.find_element_by_id("education")
    for degree in education.find_element_by_class_name("degree"):
        school = degree.find_element_by_class_name("school")
        year = degree.find_element_by_class_name("year")
        print(school.text, year.text)
    

    下面是使用 CSS 选择器的方法:

    for degree in driver.find_elements_by_css_selector("#education .degree"):
        school = degree.find_element_by_css_selector(".school")
        year = degree.find_element_by_css_selector(".year")
        print(school.text, year.text)
    

    注意:正如@Andersson 评论的那样,您应该使用this answer 中提到的方法之一检查元素(.year.school)是否存在,如果它可能会丢失。否则,此代码可能会抛出 NoSuchElementException

    【讨论】:

    • 请注意,第二个.degree 没有p.year 节点,因此您的year = degree.find_element_by_class_name("year") 将返回NoSuchElementException。您可能需要实现try/except
    • @Andersson 是的,我会添加注释
    猜你喜欢
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 2018-10-22
    • 1970-01-01
    • 1970-01-01
    • 2015-10-15
    • 2019-06-03
    • 1970-01-01
    相关资源
    最近更新 更多