Home > OS >  Selenium XPATH looking for a keyword inside of a Href that is inside of a class
Selenium XPATH looking for a keyword inside of a Href that is inside of a class

Time:07-07

I am struggling to click the first href that matches a keyword. There is at least 2 hrefs that match a keyword im using so selenium fails at clicking the element. I have tried to nominate the class and look inside that class for the Href but the syntax is incorrect. I currently have this code in a try block as it refreshes if the href is not found and tries again.

see below:

<div >
  <span >
          GlenWyvis</span>
          <h2 >
        <a href="/collections/new-whisky-arrivals/products/glenwyvis-batch-20-18-2018-vintage-2nd-release" data-product-page-link="">
          GlenWyvis Batch 02/18 | 2nd Release
        </a>
      </h2>

The Python try block I have is below:

while True:
    try:
        element = driver.find_element(By.XPATH, "//*[@class='productitem--title'] and contains(.@href, 'glenwyvis')]")
        element.click()
        break
    except NoSuchElementException:
        driver.refresh()
        time.sleep(3)

Any help is greatly appreciated.

Many thanks.

CodePudding user response:

As per the HTML:

<h2 >
    <a href="/collections/new-whisky-arrivals/products/glenwyvis-batch-20-18-2018-vintage-2nd-release" data-product-page-link="">
    GlenWyvis Batch 02/18 | 2nd Release
    </a>
</h2>

To click on the element with href starting with /collections/new-whisky-arrivals/products/glenwyvis-batch you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following locator strategies:

  • Using CSS_SELECTOR:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "h2.productitem--title > a[href^='/collections/new-whisky-arrivals/products/glenwyvis-batch']"))).click()
    
  • Using XPATH:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//h2[@class='productitem--title']/a[starts-with(@href, '/collections/new-whisky-arrivals/products/glenwyvis-batch')]"))).click()
    
  • Note: You have to add the following imports :

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    

CodePudding user response:

With minimal modifications, you could use

element = driver.find_element(By.XPATH, "//*[@class='productitem--title' and contains(a/@href, 'glenwyvis')]")

This returns the <h2> element with the desired properties.

  • Related