使用BeautifulSoup4从HTML提取字段

时间:2018-06-27 01:56:37

标签: python html beautifulsoup

我第一次使用BeautifulSoup4,并陷入了必须简单明了的事情。我有一个看起来像这样的元素标签:

<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", ... ]

对此最合适的查询是什么?

1 个答案:

答案 0 :(得分:2)

BS docs指定传递的@if($errors->get('nom')) @foreach($errors->get('nom') as $error) <li class="has-error">{{$error}}</li> @endforeach @endif 匹配任何内容,无论其值如何。这样的事情应该起作用:

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)