Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find element with certain text using Selenium with Python

Currently, I am using this and it works.

self.browser.find_element_by_xpath('//a/h4[text()="item I want"]').click()

Is there a better way to select by text? I feel like code readability suffers immensely using xpath.

Simple HTML example that can be any number of elements. The purpose is to test a specific wine that is added to the database for a functional test.

{% extends 'wine/base.html' %}
{% block content %}
    <section id="wine_content">
        <div class="cards">

            {% for wine in wines %}
            <div class="card">
                <a href="/wine/{{ wine.id }}">
                    <h4>{{ wine.name }}</h4>
                    <p>{{ wine.vintage }}</p>
                    <p>{{ wine.description}}</p>
                </a>
            </div>
            {% endfor %}

        </div>
    </section>

{% endblock %}
like image 576
Michael Bruce Avatar asked May 07 '26 07:05

Michael Bruce


1 Answers

If you want to improve the code readability, you should see to follow a page object pattern.

A first step would be to define the locator in a variable with an explicit name:

from selenium.webdriver.common.by import By
item_wine_pinot_noir = (By.XPATH, "//a/h4[text()='%s']" % "Pinneau noir")
browser.find_element(*item_wine_pinot_noir).click()
like image 96
Florent B. Avatar answered May 09 '26 21:05

Florent B.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!