我正在使用 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]
and ['2002-2008']
,我将无法分辨哪所学校对应于 year range '2002-2008'
。那么,是否可以将相应的学校名称和年份范围结合在一起?如果有其他方法可以绕过它,那也会有帮助。
您必须遍历.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 所评论的,您应该使用本答案中提到的方法之一检查元素(.year
和.school
)是否存在(如果可能丢失)。否则,此代码可能会抛出.NoSuchElementException
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句