网页元素定位技巧

结论
元素定位的核心是:优先语义,其次结构,最后才是位置。


一、定位的基本顺序

原则顺序
属性 > 文本 > 相对结构 > 位置。

原因很简单:
越接近“人理解的含义”,越不容易被改版破坏。


二、常用定位技巧(附代码)

1️⃣ 用稳定属性定位(首选)

适用场景
idnamedata-*aria-*

XPath

//*[@data-testid='review-tab']

CSS

[data-testid="review-tab"]

Selenium(Python)

driver.find_element(By.XPATH, "//*[@data-testid='review-tab']")

2️⃣ 用文本定位(适合按钮、标签)

注意
文本可能有空格,要用 normalize-space()

XPath

//button[normalize-space()='Reviews']

或:

//div[normalize-space(text())='Reviews']

3️⃣ 限定范围,再向下查找(强烈推荐)

思想
先缩小范围,再精确命中。

XPath

//*[@id='pdp-main']//button[.//text()='Reviews']

好处:
避免页面其他地方的同名元素。


4️⃣ 用 contains,但要收紧范围

不推荐裸用

//div[contains(text(),'Review')]

推荐写法

//*[@id='pdp-main']//div[contains(text(),'Review')]

5️⃣ 用 position,但只在“最后一层”

正确用法

//div[@class='list']/div[position()>2]

错误用法

//div[3]/div[2]/div[5]

原因:
中间层一变,全废。


6️⃣ 跳过不稳定层级,用 //

不稳定

//*[@id='app']/div[2]/div/div/div/span/div

稳定

//*[@id='app']//span/div

7️⃣ 多根节点兼容(A/B 测试常见)

XPath

//*[@id='app' or @id='pdp-main']//button

8️⃣ 利用结构特征,而不是编号

例子:有两个子 div 的容器

//div[count(div)=2]

三、不同工具的示例

Selenium(Python)

from selenium.webdriver.common.by import By

el = driver.find_element(
    By.XPATH,
    "//*[@id='pdp-main']//button[.//text()='Reviews']"
)

Playwright(Python)

page.locator("text=Reviews").first.click()

或:

page.locator("#pdp-main button", has_text="Reviews").click()

影刀(XPath)

//*[@id='pdp-main']//div[position()>2]

四、常见坑位提醒

1️⃣ 不要依赖 div 层级数量
React 一次渲染就会变。

2️⃣ class 经常是动态的
看到 css-xxx-123,直接放弃。

3️⃣ 文本有国际化风险
多语言页面,文本不是长期方案。

4️⃣ position 只适合列表,不适合布局

5️⃣ 能不用 XPath,就不用绝对 XPath