【问题标题】:Find partial class names in spans with Beautiful Soup使用 Beautiful Soup 在跨度中查找部分类名
【发布时间】:2019-03-21 10:02:56
【问题描述】:

此页面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-”的类?

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    根据docs,您有几种选择:

    • 使用正则表达式:

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

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

    【讨论】:

      【解决方案2】:

      你可以试试 CSS 选择器soup.select('span[class*="currentPrice-"]')

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-05-31
        • 2022-12-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-03
        • 1970-01-01
        相关资源
        最近更新 更多