python - 使用 BeautifulSoup4 从 HTML 中提取字段
问题描述
我第一次使用 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", ... ]
什么是正确的查询?
解决方案
BS 文档指定传递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']
推荐阅读
- gcc - 升级 `arm-none-eabi-gcc` 后部分 `text` 将不适合
- sql - SQL 中的 JSON 数组 - 从 JSON 数组中提取多个值
- azure - Azure 数据工厂管道到压缩 Parquet 文件中:“java.lang.OutOfMemoryError:Java heap space”
- angularjs - 将值从模态指令传递给控制器
- git - 提取git图进行处理
- python - 错误:时间数据“b'YYYY/MM/DD”与格式“%Y/%m/%d”不匹配,但它匹配
- python - 使用ran = ran [:-1]循环遍历范围(0,5);跑了!= [] 总是正确的
- ruby-on-rails - 内容丰富的 Rails 测试对象是否为空
- java - 如何提示用户执行操作
- d3.js - 在 Google Apps 脚本中使用 d3.js 绘图并将绘图嵌入到 Google Sheet、Google Sites 和 Google Slides