You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Selenium中如何用XPath的text()方法匹配任意文本?含动态定位需求

Answers to Your Selenium XPath Questions

1. How to Represent Any Text in Selenium XPath's text() Method?

If you want to target elements that contain any non-empty text content, here are practical approaches:

  • Match elements with non-empty normalized text (ignores whitespace-only content):

    //*[normalize-space(text()) != '']
    

    This selects elements where text—after stripping leading/trailing whitespace and collapsing internal spaces—isn’t empty.

  • Match elements that have any text node (even whitespace-only):

    //*[text()]
    

    Use this only if you don’t mind including elements with just spaces or newlines.

  • Target elements containing a specific substring alongside any other text:

    //*[contains(text(), 'toys')]
    

    This picks elements where "toys" appears anywhere in the text, regardless of surrounding content.

2. XPath for Matching Variable Numbers and Store Names

Your original expression targets a fixed string, but since 50 (number of toys) and Delhi (store name) are variable, here are two reliable solutions:

Option 1: Using XPath 2.0+ (Regex with matches())

Most modern browsers (Chrome, Firefox) support XPath 2.0 features in Selenium. Use a regular expression to handle variable parts:

//*[matches(normalize-space(text()), '^Showing all \d+ toys available at .+ store$')]
  • \d+ matches one or more digits (covers any number like 50, 10, 100)
  • .+ matches any sequence of characters (covers any store name like Delhi, Mumbai, Bangalore)
  • ^ and $ ensure the entire normalized text matches the pattern (prevents partial matches)

Option 2: XPath 1.0 Compatible (No Regex)

If you’re working with an environment that only supports XPath 1.0, combine starts-with(), contains(), and ends-with() to target fixed string segments:

//*[
  starts-with(normalize-space(text()), 'Showing all ')
  and contains(normalize-space(text()), ' toys available at ')
  and ends-with(normalize-space(text()), ' store')
]

This works by verifying three fixed parts of the text, letting the variable number and store name sit in between without breaking the match.


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

火山引擎 最新活动