gpt4 book ai didi

python - 从 HTML 中提取字符串

转载 作者:太空宇宙 更新时间:2023-11-03 14:25:03 24 4
gpt4 key购买 nike

我有以下元素:

<div class="column4">
Unlimited Subscription<br/> Discount for Monthly <br/> Total Amount
</div>

如何仅使用 Beautiful Soup 将三个字符串提取为三个不同的元素。不能使用字符串转换和正则表达式:

预期输出:

Unlimited Subscription
Discount for Monthly
Total Amount

最佳答案

要获取各个字符串,您可以获取 div 元素的 children 并按其类型过滤它们。

>>> bs = bs4.BeautifulSoup(html)
>>> div = bs.find(attrs={"class":"column4"})
>>> [c.strip() for c in div.children if type(c) is bs4.element.NavigableString]
['Unlimited Subscription', 'Discount for Monthly', 'Total Amount']

或者更短,使用div.stripped_strings(或者如果您不想strip,则仅使用div.strings):

>>> list(div.stripped_strings)
['Unlimited Subscription', 'Discount for Monthly', 'Total Amount']

关于python - 从 HTML 中提取字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47694234/

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