python - 从 HTML 中提取字符串

标签 python beautifulsoup

我有以下元素:

<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/

相关文章:

python - 如何在 Applescript 中运行 python 脚本?

python - 使用 BeautifulSoup4 和 Python 3.3 解析错误

python - 根据美丽汤中 child 的文本值查找标签列表

python,美汤,xml解析

python - 使用 BeautifulSoup/Python 从 html 文件中提取文本

python - 使用旁遮普语到底有什么好处

python - 如何让 Yocto 构建模块 fcntl 作为 Python 构建的一部分

Python 名称错误 : name 'file_name' is not defined

python - 不要截断列输出

python - 如何在该 html 中选择特定标签?