python - 匹配 BeautifulSoup 中的部分 id

标签 python beautifulsoup

我正在使用 BeautifulSoup。我必须找到对 <div> 的任何引用带有 ID 的标签:post-# .

例如:

<div id="post-45">...</div>
<div id="post-334">...</div>

我试过了:

html = '<div id="post-45">...</div> <div id="post-334">...</div>'
soupHandler = BeautifulSoup(html)
print soupHandler.findAll('div', id='post-*')

如何过滤?

最佳答案

您可以将函数传递给 findAll :

>>> print soupHandler.findAll('div', id=lambda x: x and x.startswith('post-'))
[<div id="post-45">...</div>, <div id="post-334">...</div>]

或正则表达式:

>>> print soupHandler.findAll('div', id=re.compile('^post-'))
[<div id="post-45">...</div>, <div id="post-334">...</div>]

关于python - 匹配 BeautifulSoup 中的部分 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2830530/

相关文章:

python - Spyder、spyder-kernels 和 python 版本兼容性?

python - 抓取并提取多个元素

python - BeautifulSoup 与 find all 只给出最后的结果

python - 如何将 .ipynb 文件上传到笔记本云实例?

python - 为什么我在这个 python 代码中得到 "AttributeError: ' str' object has no attribute 'write' “

python - 如何从具有不同 id 名称的段落中抓取文本?

python - 用Python抓取具有多个输入的网页

python - 是否可以使用 Kotlin 制作 Jython 模块?

python - Pandas - 根据其他行选择行

python - 防止获取生成器对象