gpt4 book ai didi

python - beautifulsoup,找到文本为 'price' 的第一个,然后从下一个开始获取价格

转载 作者:太空狗 更新时间:2023-10-30 00:52:19 26 4
gpt4 key购买 nike

我的 html 看起来像:

<td>
<table ..>
<tr>
<th ..>price</th>
<th>$99.99</th>
</tr>
</table>
</td>

所以我在当前表格单元格中,如何获得 99.99 值?

我到目前为止:

td[3].findChild('th')

但我需要做的是:

找到带有文本 'price' 的 th,然后获取下一个标签的字符串值。

最佳答案

在“步骤”中考虑它...假定某些 x 是您正在考虑的子树的根,

x.findAll(text='price')

是包含文本 'price' 的子树中所有项目的列表。这些项目的 parent 当然是:

[t.parent for t in x.findAll(text='price')]

如果你只想保留那些“名字”(标签)是'th'的,那当然

[t.parent for t in x.findAll(text='price') if t.parent.name=='th']

并且您想要那些的“下一个 sibling ”(但前提是他们也是'th'),所以

[t.parent.nextSibling for t in x.findAll(text='price')
if t.parent.name=='th' and t.parent.nextSibling and t.parent.nextSibling.name=='th']

在这里您可以看到使用列表理解的问题:重复太多,因为我们无法将中间结果分配给简单的名称。因此,让我们切换到一个很好的旧循环......:

编辑:添加了对父 th 和“下一个兄弟”之间的文本字符串的容忍度,以及对后者是 td< 的容忍度 相反,根据 OP 的评论。

for t in x.findAll(text='price'):
p = t.parent
if p.name != 'th': continue
ns = p.nextSibling
if ns and not ns.name: ns = ns.nextSibling
if not ns or ns.name not in ('td', 'th'): continue
print ns.string

我已经添加了 ns.string,当且仅当它们只是文本(没有进一步的嵌套标签)时,它将给出下一个兄弟的内容——当然你可以进一步分析这一点,取决于你的应用程序的需要!-)。同样,我想你不会只是做 print,而是做一些更聪明的事情,但我给你的是结构。

谈到结构,请注意我两次使用 if...: continue:与反转 if 的条件和缩进的替代方案相比,这减少了嵌套循环中的所有以下语句——“扁平优于嵌套”是 Python 之禅中的一个公案(import this 在交互式提示下查看所有内容并进行冥想;-) .

关于python - beautifulsoup,找到文本为 'price' 的第一个,然后从下一个开始获取价格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3376803/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com