【发布时间】:2013-01-28 10:54:57
【问题描述】:
我有很多 html 响应代码,在某些地方有这个部分:
</td>
</tr>
<input id="hiddenloginurl" type="hidden" name="loginurl" value="/sensor.htm?id=10240">
</table>
如何解析 html 代码并使用 python 获取此 id?问题是,在每次新的 api 调用中,id 都会改变。
【问题讨论】:
我有很多 html 响应代码,在某些地方有这个部分:
</td>
</tr>
<input id="hiddenloginurl" type="hidden" name="loginurl" value="/sensor.htm?id=10240">
</table>
如何解析 html 代码并使用 python 获取此 id?问题是,在每次新的 api 调用中,id 都会改变。
【问题讨论】:
Beautiful Soup 提供了一些用于导航、搜索和修改解析树的简单方法和 Pythonic 习惯用法: 剖析文档并提取您需要的内容。它不需要 编写应用程序需要很多代码
Beautiful Soup 自动将传入的文档转换为 Unicode 并将传出文档转换为 UTF-8。你不必考虑 编码,除非文档没有指定编码并且 Beautiful Soup 无法自动检测到一个。然后你只需要指定 原始编码。
Beautiful Soup 位于流行的 Python 解析器(如 lxml 和 html5lib,允许您尝试不同的解析策略或 以速度换取灵活性。
另见类似问题:Extracting an attribute value with beautifulsoup
inputTag = soup.find(attrs={"name": "stainfo"})
output = inputTag['value']
【讨论】: