我有以下元素:
<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/