使用BeautifulSoup4从HTML中提取字段

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

我第一次使用BeautifulSoup4,并且遇到了必须简单明了的事情。我有一个Element Tag,看起来像这样:

<td class="stage" data-value="phase3">\n                                    
\n    Phase 3\n<svg height="5" viewbox="1 1 95 5" width="95" 
xmlns="http://www.w3.org/2000/svg">\n<g fill="none" transform="translate(1 1 
)">\n<rect fill="#911C36" height="5" rx="2" width="15"></rect>\n<rect 
fill="#D6A960" height="5" rx="2" width="15" x="16"></rect>\n<rect 
fill="#E7DE6F" height="5" rx="2" width="15" x="32"></rect>\n<rect fill="#ddd" 
height="5" rx="2" width="15" x="48"></rect>\n<rect fill="#ddd" height="5" 
rx="2" width="15" x="64"></rect>\n<rect fill="#ddd" height="5" rx="2" 
width="15" x="80"></rect>\n</g>\n</svg> </td>

我想从“数据值”字段和填充颜色列表中提取值“phase3”,例如

[ "#911C36", "#D6A960", ... ]

有什么正确的查询?

python html beautifulsoup
1个回答
2
投票

BS docs指定传递True匹配任何值,无论值多少。这样的事情应该有效:

from bs4 import BeautifulSoup


soup = BeautifulSoup("""
<td class="stage" data-value="phase3">\n                                    
\n    Phase 3\n<svg height="5" viewbox="1 1 95 5" width="95" 
xmlns="http://www.w3.org/2000/svg">\n<g fill="none" transform="translate(1 1 
)">\n<rect fill="#911C36" height="5" rx="2" width="15"></rect>\n<rect 
fill="#D6A960" height="5" rx="2" width="15" x="16"></rect>\n<rect 
fill="#E7DE6F" height="5" rx="2" width="15" x="32"></rect>\n<rect fill="#ddd" 
height="5" rx="2" width="15" x="48"></rect>\n<rect fill="#ddd" height="5" 
rx="2" width="15" x="64"></rect>\n<rect fill="#ddd" height="5" rx="2" 
width="15" x="80"></rect>\n</g>\n</svg> </td>
""", "html.parser")

colors = [x["fill"] for x in soup.findAll("rect", {"fill": True})]
data_vals = [x["data-value"] for x in soup.findAll("td", {"data-value": True})]

print(colors)
print(data_vals)

输出:

['#911C36', '#D6A960', '#E7DE6F', '#ddd', '#ddd', '#ddd']
['phase3']
© www.soinside.com 2019 - 2024. All rights reserved.