这通常是由于BeautifulSoup选择器返回了匹配的第一个元素。因此,需要使用find_all()或select()方法来获取特定标签或类名的所有匹配元素,并从中选择所需的元素。
示例代码:
# 导入BeautifulSoup库
from bs4 import BeautifulSoup
# 假设以下是HTML页面的文本
html_doc = "The Dormouse's story The Dormouse's story
Once upon a time there were three little sisters; and their names were Elsie,Lacie andTillie;and they lived at the bottom of a well.
...
"
# 创建BeautifulSoup对象
soup = BeautifulSoup(html_doc, 'html.parser')
# 通过类名获取所有的p元素
all_p = soup.find_all('p', class_='story')
# 打印所有匹配到的p元素
for item in all_p:
print(item.text)
在以上代码中,我们使用了find_all()方法来获取所有具有类名“story”的p元素,并打印了所有匹配到的元素。