Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Build XPATH expression to get and click button element

I’m building a scraper with selenium, and I got it up and running except for one data field I’m missing. I need to first push a button, then get the value. But I haven’t been able to push the button, because I can’t seem to build the correct xpath expression to get it with selenium,

The url is this one: https://www.ikea.com/mx/es/p/kallax-estante-blanco-80275887/

And I need to click the button "Medidas" (scroll halfway through the page, right between "Detalles del producto" and "Productos similares") to open a side panel and get the info I need.
But so far, I haven’t been able to set the correct XPATH expression for the button.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I tried with

driver.find_element_by_xpath(
     "//button[@class='range-revamp-chunky-header']"
 ).click()

But this way it clicked the first button ("Detalles del producto")

Also tried with something like

driver.find_element_by_xpath(
     "//button[@class='range-revamp-chunky-header' AND @text='Medidas']"
 ).click()

But I haven’t been able to make it work, I just got this error:

Message: no such element: Unable to locate element: {"method":"xpath","selector":"//button[@class='range-revamp-chunky-header' and @text='Medidas']"}

By the way, the list of buttons is dynamic… sometimes, there can be 1, 2, 3 or 4 buttons with the same class, only difference I can see is the text of the button, so getting always the 2nd button with that class (like in the URL provided) won’t always work.

>Solution :

To click on the element with text as Medidas you can use the following Locator Strategy:

  • Using xpath:

    driver.find_element(By.XPATH, "//span[text()='Medidas']").click()
    

Ideally you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following Locator Strategy:

  • Using XPATH:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//*[contains(., 'login or register')]"))).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
    
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading