Home > Software design >  Python Selenium How to find elements by XPATH with info from TAG and SUB TAG
Python Selenium How to find elements by XPATH with info from TAG and SUB TAG

Time:03-05

HTML:

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

       <a  href="url">
            <h3 >
              <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 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.

CodePudding user response:

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