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 %}
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With