python - 使用 BeautifulSoup 搜索具有多个空格和通配符的类标签

标签 python beautifulsoup findall

我正在尝试使用 BeautifulSoup 查找所有类属性以“foo bar”开头的 div 容器。我曾希望以下方法会起作用:

from bs4 import BeautifulSoup

import re

soup.findAll('div',class_=re.compile('^foo bar'))

但是,类定义似乎被分隔成一个列表,如 ['foo','bar'],这样正则表达式无法完成我的任务。有什么办法可以完成这个任务吗? (我查看了许多其他帖子,但没有找到可行的解决方案)

最佳答案

您可以使用带有 function that needs to return True or False 的语法, lambda 也可以做到这一点:

from bs4 import BeautifulSoup as soup
html = '''
<div class="foo bar bing"></div>
<div class="foo bang"></div>
<div class="foo bar1 bang"></div>
'''
soup = soup(html, 'lxml')
res = soup.find_all('div', class_=lambda s:s.startswith('foo bar '))
print(res)
>>> [<div class="foo bar bing"></div>]

res = soup.find_all('div', class_=lambda s:s.startswith('foo bar')) # without space
print(res)
>>> [<div class="foo bar bing"></div>, <div class="foo bar1 bang"></div>]

另一种可能的函数语法:

def is_a_match(clas):
    return clas.startswith('foo bar')

res = soup.find_all('div', class_=is_a_match)

也许这个答案对您也有帮助:https://stackoverflow.com/a/46719313/6655211

关于python - 使用 BeautifulSoup 搜索具有多个空格和通配符的类标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36996722/

相关文章:

python - 当 groupby 另一个时, Pandas 在组中获得最少的一列

python - 使用python动态浏览(Mechanize、Beautifulsoup...)

帮助中列出的 Python 模块与 pip 找到的不同

arrays - Groovy 过滤器二维数组

Python 正则表达式 字符之间的匹配

python - 正则表达式返回所有字符,直到向后搜索 "/"

python - WebDriverWait 多个条件(或逻辑评估)

python - Google App Engine 启动器未运行应用程序

python - 无法让 Django Rest Framework ViewSet 识别用户的权限

python - 如何使用 BeautifulSoup 收集数据 python