要让BeautifulSoup返回元素的子元素,可以使用find_all方法来查找子元素。
以下是一个示例代码:
from bs4 import BeautifulSoup
html = """
BeautifulSoup Example
Web Scraping with BeautifulSoup
BeautifulSoup is a Python library for parsing HTML and XML documents.
"""
soup = BeautifulSoup(html, 'html.parser')
container = soup.find(id='container')
children = container.find_all()
for child in children:
print(child)
在上面的代码中,首先使用BeautifulSoup解析HTML文档。然后使用find方法找到id为"container"的div元素。接下来使用find_all方法查找div元素的所有子元素,并使用循环打印每个子元素。
运行以上代码,将输出以下结果:
Web Scraping with BeautifulSoup
BeautifulSoup is a Python library for parsing HTML and XML documents.
因此,通过使用find_all方法,可以获取元素的子元素。