我正在尝试查找特定div
中子元素的数量。在BeautifulSoup中,您可以调用contents
方法来排序列表中的所有子项(在保留功能的同时,您仍然可以对列表中的每个项执行.find('something_to_find')
(。硒有类似的东西吗?
在Selenium中,您可以使用XPath
或CSS Selector
来创建更复杂的规则。
似乎可以使用XPath//div/*
或CSS选择器div > *
来获取div
中的所有子项
获取所有(不仅仅是子项(xpath//div//*
和CSS选择器div *
使用XPath,您还可以获得具有一些限制的子级,例如
CCD_ 11-内有CCD_ 12的儿童。
//div/*[text()="Hello"]
-具有文本Hello
的儿童。
或者甚至嵌套//div/*[b[text()="Title"]]
-具有文本Title
的<b>
的子级。
示例代码
from selenium import webdriver
driver = webdriver.Firefox()
html = """
<html>
<head></head>
<body>
<div>
<h1><b>Title</b></h1>
<span>Hello</span>
<span>World<b> !!!</b></span>
<p>Text</p>
</div>
</body>
</html>
"""
driver.get("data:text/html;charset=utf-8,{html}".format(html=html))
print('--- children ---')
for item in driver.find_elements_by_xpath('//div/*'):
print(item.tag_name)
print('--- all ---')
for item in driver.find_elements_by_xpath('//div//*'):
print(item.tag_name)
print('--- children ---')
for item in driver.find_elements_by_css_selector('div > *'):
print(item.tag_name)
print('--- all ---')
for item in driver.find_elements_by_css_selector('div *'):
print(item.tag_name)
print('--- children with <b> ---')
for item in driver.find_elements_by_xpath('//div/*[b]'):
print(item.tag_name)
print('--- children with text "Hello" ---')
for item in driver.find_elements_by_xpath('//div/*[text()="Hello"]'):
print(item.tag_name)
print('--- children with <b> which have text "Hello" ---')
for item in driver.find_elements_by_xpath('//div/*[b[text()="Title"]]'):
print(item.tag_name)
结果:
--- children ---
h1
span
span
p
--- all ---
h1
b
span
span
b
p
--- children ---
h1
span
span
p
--- all ---
h1
b
span
span
b
p
--- children with <b>---
h1
span
--- children with <b>---
span
--- children with <b> which have text "Hello" ---
h1