获取BeautifulSoup Class属性值

问题描述 投票:0回答:1

我想使用BeautifulSoup从下面的结构html内容中获取仅3.5、4.3和2.5的值。请帮忙如何废弃该值。

<div class="abc">3.5<img class="def" src=''</div>
<div class="abc">4.3<img class="def" src=''</div>
<div class="abc">2.5<img class="def" src=''</div>
python beautifulsoup
1个回答
0
投票

这里有一个关于如何实现这一目标的快速片段。由于您没有提供任何代码,我不知道您的 html 来自哪里,所以我只是将您给定的 html 设置为变量。

from bs4 import BeautifulSoup

html_content = """
<div class="abc">3.5<img class="def" src=''</div>
<div class="abc">4.3<img class="def" src=''</div>
<div class="abc">2.5<img class="def" src=''</div>
"""

# Initialize html parser
soup = BeautifulSoup(html_content, 'html.parser')

# Find all div elements with class 'abc'
div_elements = soup.find_all('div', class_='abc')

# Extract the text from each div element and print the value
for div in div_elements:
    value = div.text.strip()  # Get the text and remove leading/trailing spaces
    print(value)

这将打印出:

3.5
4.3
2.5
© www.soinside.com 2019 - 2024. All rights reserved.