Home > Blockchain >  How to identify an element with a specific text and a specific title using Selenium and Python
How to identify an element with a specific text and a specific title using Selenium and Python

Time:08-08

I have the following DOM

<a  title="Inno 3D GeForce RTX 3080 10GB GDDR6X X3 LHR Κάρτα Γραφικών PCI-E x16 4.0 με HDMI και 3 DisplayPort" data-e2e-testid="sku-price-link" href="/s/35993359/Inno-3D-GeForce-RTX-3080-10GB-GDDR6X-X3-LHR-Κάρτα-Γραφικών-PCI-E-x16-4-0-με-HDMI-και-3-DisplayPort-N30803-106X-1810VA44H.html">
    <span>από</span>
    871,28 €
</a>

As you can see it has a class and a title. There are other elements in the page that have the same a class (js-sku-link sku-link) but I want to be able to define based on the title which one I want. In this case I want the one that it has in title the text RTX 3080. I tried the following without any luck

driver.find_element_by_xpath('//div[@data-e2e-testid="sku-price-link" and text()="RTX 3080"]').text
driver.find_element_by_xpath("//a[@title='6950']")

CodePudding user response:

Try this XPath expression:

driver.find_element_by_xpath('//a[@data-e2e-testid="sku-price-link" and contains(@title,"RTX 3080")]').text

The result is the text content of the <a> element:

από
871,28 €

CodePudding user response:

As per the HTML:

<a  title="Inno 3D GeForce RTX 3080 10GB GDDR6X X3 LHR Κάρτα Γραφικών PCI-E x16 4.0 με HDMI και 3 DisplayPort" data-e2e-testid="sku-price-link" href="/s/35993359/Inno-3D-GeForce-RTX-3080-10GB-GDDR6X-X3-LHR-Κάρτα-Γραφικών-PCI-E-x16-4-0-με-HDMI-και-3-DisplayPort-N30803-106X-1810VA44H.html">
    <span>από</span>
    871,28 €
</a>

The element is an <a> tag and a clickable element. To identify the clickable element based on the partial value of the title attribute i.e. RTX 3080 you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following locator strategies:

  • Using CSS_SELECTOR and title:

    element = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a[title*='RTX 3080']")))
    
  • Using XPATH and partial title:

    element = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[contains(@title, 'RTX 3080')]")))
    
  • 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:

Which browser you are using? You can inspect the specific element and get the Xpath of the value of the element you are inspecting in the browser.

  • Related