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

Python Selenium:定位同时包含两种样式的元素

定位Facebook Marketplace的三点按钮元素

目标元素的HTML代码如下:

<i data-visualcompletion="css-img" class="x1b0d499 xep6ejk" style="background-image: url(&quot;https://static.xx.fbcdn.net/rsrc.php/v3/yd/r/A6Wu9TeIieI.png&quot;); background-position: 0px -1304px; background-size: auto; width: 16px; height: 16px; background-repeat: no-repeat; display: inline-block;"></i>

由于style属性中的background-position、background-image等属性值会频繁变化,直接使用完整style属性值定位不可行,例如以下写法无法稳定生效:

style ='background-image: url(&quot;https://static.xx.fbcdn.net/rsrc.php/v3/yd/r/A6Wu9TeIieI.png&quot;); background-position: 0px -1304px; background-size: auto; width: 16px; height: 16px; background-repeat: no-repeat; display: inline-block;'
driver.find_elements(By.CSS_SELECTOR, f"i[style='{style}']")

多条件匹配固定style片段的解决方案

1. XPath 实现逻辑与匹配

通过contains结合and逻辑,逐个匹配固定不变的style片段,避免因动态属性变化导致定位失效:

driver.find_elements(By.XPATH, "//i[contains(@style, 'width: 16px;') and contains(@style, 'height: 16px;') and contains(@style, 'background-repeat: no-repeat;') and contains(@style, 'display: inline-block;')]")

如果需要进一步缩小范围,可结合元素的class属性追加条件:

driver.find_elements(By.XPATH, "//i[@class='x1b0d499 xep6ejk' and contains(@style, 'width: 16px;') and contains(@style, 'height: 16px;') and contains(@style, 'background-repeat: no-repeat;') and contains(@style, 'display: inline-block;')]")

2. CSS选择器 实现逻辑与匹配

利用CSS选择器的*=(属性值包含指定字符串)语法,多个条件并列即可实现逻辑与:

driver.find_elements(By.CSS_SELECTOR, "i[style*='width: 16px;'][style*='height: 16px;'][style*='background-repeat: no-repeat;'][style*='display: inline-block;']")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 13:05:25