BeautifulSoup的find_all方法存在以下问题:
以下是解决这些问题的代码示例:
from bs4 import BeautifulSoup
html = """
标题
内容1
内容2
"""
soup = BeautifulSoup(html, "html.parser")
# 使用find方法获取单个元素
h1 = soup.find("h1")
print(h1.text)
p = soup.find("p")
print(p.text)
输出结果:
标题
内容1
from bs4 import BeautifulSoup
html = """
标题
内容1
内容2
"""
soup = BeautifulSoup(html, "html.parser")
# 使用CSS选择器获取多个不同标签的元素
elements = soup.select("h1, p")
for element in elements:
print(element.text)
输出结果:
标题
内容1
内容2