从产品帮助中检索美丽的汤代码

2024-09-27 07:20:51 发布

您现在位置:Python中文网/ 问答频道 /正文

一个网页包含我需要检索的产品代码,它位于以下HTML部分:

<table...>
<tr>
 <td>
 <font size="2">Product Code#</font>
 <br>
 <font size="1">2342343</font>
 </td>

</tr>
</table>

所以我想最好的方法是首先引用文本值为'productcode#'的html元素,然后在TD中引用第二个字体标记。在

有什么想法?在


Tags: 方法代码文本br网页size产品html
3条回答

我的策略是:

  • 查找与字符串“Product Code”匹配的文本节点
  • 对于每个这样的节点,获取父元素<font>并找到父元素的下一个同级<font>元素
  • 将同级元素的内容插入列表中

代码:

from BeautifulSoup import BeautifulSoup


html = open("products.html").read()
soup = BeautifulSoup(html)

product_codes = [tag.parent.findNextSiblings('font')[0].contents[0]
                 for tag in 
                 soup.findAll(text='Product Code#')]

您可以使用此regex(或类似的):

<td>\n\ <font\ size="2">Product\ Code\#</font>\n\ <br>\n\ <font\ size="1">(?<ProductCode>.+?)</font>\n\ </td>

你可以根据你的RegExp引擎删除一些转义。。。我当时很谨慎。在

假设soup是您的BeautifulSoup实例:

int(''.join(soup("font", size="1")[0](text=True)))

或者,如果需要获取多个产品代码:

^{pr2}$

相关问题 更多 >

    热门问题