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

Selenium中如何用text_to_be_present_in_element检查元素文本前缀/后缀?

Answer

Great question! Let's break this down clearly for you:

1. Using text_to_be_present_in_element for partial text checks

Good news—your current code is already doing exactly what you need! The text_to_be_present_in_element expected condition does not require a full text match; it checks if the target element's text contains the substring you pass in.

So your existing line:

wait = WebDriverWait(driver, 10)
wait.until(expected_conditions.text_to_be_present_in_element((By.ID, 'equity_timeStamp'),'As on'))

will work perfectly to verify that the element contains the "As on" prefix. You could also swap in 'IST' to check the suffix instead—no modifications needed. This is the simplest built-in solution for your use case.

2. Using regular expressions (without custom condition classes)

If you need more precise validation (like ensuring the text starts with "As on" or ends with "IST", rather than just containing those strings), you don't have to create a custom condition class. Instead, use a lambda expression with WebDriverWait and Python's re module for regex matching.

First, make sure to import the regex module:

import re

Check if text starts with "As on":

wait.until(lambda driver: re.match(r"^As on.*", driver.find_element(By.ID, 'equity_timeStamp').text))

Check if text ends with "IST":

wait.until(lambda driver: re.match(r".*IST$", driver.find_element(By.ID, 'equity_timeStamp').text))

This approach is far more concise than writing a full custom expected condition class while still giving you regex-level flexibility.

Quick recap

  • For basic substring checks (prefix/suffix presence), stick with text_to_be_present_in_element—your original code is already correct.
  • For regex-specific validation, use a lambda with re.match() as shown above.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 00:18:12