Python Selenium How to find elements by XPATH with info from TAG and SUB TAG

Viewed 591

HTML:

<div id="related">
      <a class="123" href="url">
            <h3 class="456">
              <span id="id00" aria-label="TEXT HERE">
              </span>
            </h3>
        </a>

       <a class="123" href="url">
            <h3 class="456">
              <span id="id00" aria-label="NOT HERE">
              </span>
            </h3>
        </a>
</div>

I'm trying to find & click on <a (inside the div id="related" with class="123" AND where SPAN aria-label contains "TEXT"

 items = driver.find_elements(By.XPATH, "//div[@id='related']//a[@class='123'][contains(@href, 'url')]//span[contains(@aria-label, 'TEXT']")

But it's not finding the href, it's only finding the span.

then I want to do:

items[3].click()

How can I do that.

1 Answers

Your XPath has some typo problems.
Try this:

 items = driver.find_elements(By.XPATH, "//div[@id='related']//a[@class='123'][contains(@href,'watch?v=')]//span[contains(@aria-label,'TEXT')]")

This will give you the span element inside the presented block.
To locate the a element you should use another XPath.
UPD
To find all the a elements inside div with @id='related' and containing span with specific aria-label attribute can be clearly translated to XPath like this:

 items = driver.find_elements(By.XPATH, "//div[@id='related']//a[@class='123' and .//span[contains(@aria-label,'TEXT')]]")
Related