You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Beautiful Soup 4直接按class+aria-label组合查找元素?

解决方案

你可以直接利用BeautifulSoup的精准匹配能力,不用遍历或正则处理父元素,以下两种高效方法都能满足需求:

方法1:使用find()方法指定多条件

通过find()的class_参数匹配类名,attrs参数指定aria-label属性,直接定位目标元素,不存在则返回None:

from bs4 import BeautifulSoup

# 假设soup是已解析好的BeautifulSoup对象
target_item = soup.find(
    "li",
    class_="nd-list__item in-feat-item",
    attrs={"aria-label": "rooms"}  # 替换为你需要的aria-label值
)

方法2:使用CSS选择器select_one()

CSS选择器支持同时匹配类和属性,语法更简洁,select_one()会返回第一个匹配的元素,无匹配时返回None:

target_item = soup.select_one('li.nd-list__item.in-feat-item[aria-label="rooms"]')

这两种方法都是直接精准定位目标元素,无需遍历所有列表项,完全避开了顺序变化的问题,效率远高于find_all()遍历。

内容的提问来源于stack exchange,提问作者Scolpe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 05:46:09