Python BeautifulSoup 选择属性开头的所有元素

标签 python beautifulsoup

我想选择至少具有一个以“responsive-”开头的属性的所有元素

<div reponsive-devices="desktop"></div> #Select this
<ul responsive-os="android"></ul> # Select this
<div class="responsive-"></div> # DON'T select this

我已经尝试过这个:Can I select all elements whose attribute names (not values) start with a certain string?但这对我没有帮助。

有人知道吗?

最佳答案

这并不简单,但您可以迭代标记并检查是否有任何属性以 responsive 开头。

参见下面的代码:

from bs4 import BeautifulSoup

data = '''<div responsive-devices="desktop"></div>
<ul responsive-os="android"></ul>
<div class="responsive-"></div>'''

soup = BeautifulSoup(''.join(data))

responsive_tag_list = soup.findAll(
                lambda tag:
                any([i.startswith('responsive-') for i in tag.attrs])
                )

print(responsive_tag_list)

输出:

[<div responsive-devices="desktop"></div>, <ul responsive-os="android"></ul>]

关于Python BeautifulSoup 选择属性开头的所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56505565/

相关文章:

Python - telnet - 自动化APC PDU

python - 如何使用 PIL 减小图像文件大小

python - Jupyter Notebook : Import . ipynb 文件并在其他 .ipynb 文件中访问它的方法给出错误

python - 使用 Beautifulsoup 从 url 中提取链接

python - 使用 beautifulsoup,如何在 html 页面中引用表行

python - python中的稀疏分配列表

python - time.sleep 和 suspend(即待机和休眠)

python - 无法将 Beautiful Soup 安装到 Python 2,因为我已经将它安装在 Python 3 中,但我也无法导入或卸载它

javascript - 使用 Requests/BeautifulSoup 抓取网站时绕过脚本响应

python - 异常类型: MissingSchema/beautifulsoup