如何用Beautiful Soup提取金额并剔除嵌套的project-votes span元素?
解决Beautiful Soup提取金额文本的问题
方法1:直接提取外层span的子文本节点
金额是外层span的直接文本内容,嵌套的<span class="project-votes">是独立子元素,我们可以通过筛选文本节点来提取金额:
for target_span in soup.find_all("span", {"class": "budget-list__data__number budget-list__number show-for-medium"}): # 筛选外层span的直接文本节点,去除空白后拼接 amount_text = ' '.join([text.strip() for text in target_span.contents if isinstance(text, str) and text.strip()]) print(amount_text) # 输出示例:4 000 €
方法2:移除嵌套span后提取文本
先定位并移除嵌套的投票span元素,再获取清理后的文本:
for target_span in soup.find_all("span", {"class": "budget-list__data__number budget-list__number show-for-medium"}): # 找到嵌套的project-votes元素 vote_span = target_span.find("span", class_="project-votes") if vote_span: vote_span.decompose() # 从文档树中彻底移除该元素 # 获取去除多余空白的文本 amount_text = target_span.get_text(strip=True) print(amount_text)
为什么span.clear()无效?
clear()方法会删除当前元素的所有子节点和文本内容,执行后外层span会变成空标签,自然无法获取金额。你需要的是移除特定的嵌套元素,而非清空全部内容。
内容的提问来源于stack exchange,提问作者Weierstraß Ramirez
相关产品推荐
相关产品推荐

