Home >Backend Development >Python Tutorial >How to Find Elements with Specific Text in Selenium WebDriver Using Python (Case-Insensitive)?

How to Find Elements with Specific Text in Selenium WebDriver Using Python (Case-Insensitive)?

Barbara Streisand
Barbara StreisandOriginal
2024-10-29 04:36:02552browse

How to Find Elements with Specific Text in Selenium WebDriver Using Python (Case-Insensitive)?

Identifying Elements with Specific Text in Selenium WebDriver (Python)

Locating elements with specific text content in Selenium WebDriver can pose challenges, especially when dealing with JavaScript interfaces. One common approach involves utilizing XPath expressions, but it may exhibit case sensitivity limitations.

To overcome this, a modified XPath expression can be employed:

<code class="python">driver.find_elements_by_xpath("//*[contains(text(), 'My Button')]")</code>

This expression searches for all elements within the document that contain the text "My Button," regardless of case.

For situations where elements are nested within other elements, such as:

<code class="html"><div class="outer"><div class="inner">My Button</div></div></code>

it's important to ensure that the target element is the innermost element containing the desired text. To do this, you can exclude elements that are parents of other elements containing the same text:

<code class="python">elements = driver.find_elements_by_xpath("//*[contains(text(), 'My Button')]")
for element in elements:
    if element.find_element_by_xpath('.//*[contains(text(), 'My Button')]'):
        continue
    else:
        # Perform actions on the current element</code>

The above is the detailed content of How to Find Elements with Specific Text in Selenium WebDriver Using Python (Case-Insensitive)?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn