此页面 https://www.kijiji.ca/v-1-bedroom-apartments-condos/ville-de-montreal/1-chambre-chauff-eau-chaude-incl-vsl-514-856-0038/1334431659 包含以下span类:
<span class="currentPrice-3131760660"><span content="800.00">800,00 $</span>
我正在尝试自动提取价格(在本例中为 800 美元(。然而,随着时间的推移,"currentPrice-"后面的数字会发生变化,我的 Python 脚本将停止工作。我正在使用这个美丽的汤功能:
soup.find_all('span', {'class' : 'currentPrice-3131760660'})
如何使用find_all提取类名的部分匹配项,例如包含字符串"currentPrice-"的所有类?
根据文档,您有以下几种选择:
-
使用正则表达式:
soup.find_all('span', attrs={'class': re.compile('^currentPrice.*')})
-
使用函数:
soup.find_all('span', attrs={'class': lambda e: e.startswith('currentPrice') if e else False})
你可以尝试使用CSS选择器soup.select('span[class*="currentPrice-"]')