如何在使用 python 3 和 beautifulsoup 4 时以相同的排列方式获取所有文本。我尝试了一个 for 循环,但它没有用。
from bs4 import BeautifulSoup
data = """
<body>
<div id="Select">
<h1 id="wall">
First
</h1>
</div>
</div>
<div id="color_acts">
<p id="acts_h">
Choose
</p>
<p id="actshead">
Color
</p>
<p id="acts">
Blue
</p>
</div>
<div id="Select">
<h1 id="wall">
Second
</h1>
</div>
</div>
<div id="color_acts">
<p id="acts_h">
Choose
</p>
<p id="actshead">
Color
</p>
<p id="acts">
Green
</p>
</div>
</body>
"""
soup = BeautifulSoup(data, "html.parser")
for Colors in soup.find_all('div', id='Select'):
CC = Colors.find('h1').text
print(CC)
SS = soup.find('div', id='color_acts')
print(SS)
我的输出:
First
<div id="color_acts">
<p id="acts_h">
Choose
</p>
<p id="actshead">
Color
</p>
<p id="acts">
Blue
</p>
</div>
Second
<div id="color_acts">
<p id="acts_h">
Choose
</p>
<p id="actshead">
Color
</p>
<p id="acts">
Blue
</p>
</div>
我的预期输出:
First
Choose
Color
Blue
Second
Choose
Color
Green
请注意,我的预期输出是蓝色然后是绿色,但实际输出只有两次蓝色。如何使输出具有正确的颜色并防止打印 html 标签?