使用Beautiful Soup提取class属性值的方法是使用find_all
函数,并通过class_
参数指定要提取的class属性值。
以下是一个示例代码:
from bs4 import BeautifulSoup
html = """
Hello, Beautiful Soup!
Beautiful Soup is a Python library for pulling data out of HTML and XML files.
"""
soup = BeautifulSoup(html, 'html.parser')
# 提取所有class为"title"的元素
titles = soup.find_all(class_="title")
for title in titles:
print(title.text)
# 提取所有class为"description"的元素
descriptions = soup.find_all(class_="description")
for description in descriptions:
print(description.text)
输出结果:
Hello, Beautiful Soup!
Beautiful Soup is a Python library for pulling data out of HTML and XML files.
在上面的代码中,我们使用find_all
函数来查找所有具有特定class属性值的元素。通过class_
参数指定要查找的class属性值。然后,我们可以使用text
属性来获取元素的文本内容。