使用 Beautiful Soup 帮助从 HTML 检索产品代码
一个网页有一个我需要检索的产品代码,它位于以下 HTML 部分中:
<table...>
<tr>
<td>
<font size="2">Product Code#</font>
<br>
<font size="1">2342343</font>
</td>
</tr>
</table>
所以我想最好的方法是首先引用文本值“产品代码#”的 html 元素,然后引用TD 中的第二个字体标签。
有想法吗?
A webpage has a product code I need to retrive, and it is in the following HTML section:
<table...>
<tr>
<td>
<font size="2">Product Code#</font>
<br>
<font size="1">2342343</font>
</td>
</tr>
</table>
So I guess the best way to do this would be first to reference the html element with the text value 'Product Code#', and then reference the 2nd font tag in the TD.
Ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我的策略是:
元素并查找父级的下一个兄弟
code> element
代码:
My strategy is:
<font>
element and find the parent's next sibling<font>
elementThe code:
假设
soup
是您的BeautifulSoup
实例:或者,如果您需要获取多个产品代码:
Assuming
soup
is yourBeautifulSoup
instance:Or, if you need to get multiple product codes:
您可以使用此正则表达式(或类似的东西):
\n\ Product\ Code\#\n\.+?)\n\
\ n\ (?
您可能可以删除一些转义符,具体取决于你的正则表达式引擎...我很谨慎。
You could use this regex (or something similar):
<td>\n\ <font\ size="2">Product\ Code\#</font>\n\ <br>\n\ <font\ size="1">(?<ProductCode>.+?)</font>\n\ </td>
You could probably remove some of the escapes depending on your RegExp engine... I was being cautious.
不要使用正则表达式来解析 HTML。我将使用以下 XPATH 来完成此任务:
或者,如果字体大小属性不能保证存在且等于 1:
Don't use regular expressions to parse HTML. I would use the following XPATH for this task:
Or, if the font size attribute is not guaranteed to be there and equal to 1: