首页 > 解决方案 > 使用 Beautiful Soup 在跨度中查找部分类名

问题描述

此页面https://www.kijiji.ca/v-1-bedroom-apartments-condos/ville-de-montreal/1-chambre-chauff-eau-chaude-incl-vsl-514-856-0038/1334431659包含这个跨度类:

<span class="currentPrice-3131760660"><span content="800.00">800,00 $</span>

我正在尝试自动提取价格(在这种情况下为 800 美元)。然而,随着时间的推移,“currentPrice-”之后的数字会发生变化,我的 Python 脚本将停止工作。我正在使用这个美丽的汤功能:

soup.find_all('span', {'class' : 'currentPrice-3131760660'})

如何使用 find_all 提取类名的部分匹配项,例如包含字符串“currentPrice-”的所有类?

标签: pythonbeautifulsoup

解决方案


根据文档,您有几个选择:

  • 使用正则表达式:

    soup.find_all('span', attrs={'class': re.compile('^currentPrice.*')})
    
  • 使用一个函数:

    soup.find_all('span',
                  attrs={'class': lambda e: e.startswith('currentPrice') if e else False})
    

推荐阅读