构建 XPATH 表达式以获取并单击按钮元素

Build XPATH expression to get and click button element

我正在用 selenium 构建一个 scraper,我把它弄好了 运行 除了一个数据字段我丢失了。我需要先按下一个按钮,然后获取值。但是我一直无法按下按钮,因为我似乎无法构建正确的 xpath 表达式来使用 selenium 获取它,

url是这个:https://www.ikea.com/mx/es/p/kallax-estante-blanco-80275887/

我需要单击“Medidas”按钮(滚动页面的一半,就在“Detalles del producto”和“Productos similares”之间)以打开侧面板并获取我需要的信息。 但是到目前为止,我还没有能够为按钮设置正确的 XPATH 表达式。

我试过

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

但是这样它就点击了第一个按钮(“Detalles del producto”)

也试过

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

但是我没能让它工作,我只是得到了这个错误:

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

顺便说一句,按钮列表是动态的...有时,可以有 1、2、3 或 4 个按钮具有相同的 class,唯一不同的是我能看到的文本按钮,因此始终使用 class 的第二个按钮(如提供的 URL)并不总是有效。

要单击文本为 Medidas 的元素,您可以使用以下 :

  • 使用 xpath:

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

理想情况下你需要诱导 WebDriverWait for the and you can use either of the following :

  • 使用 XPATH:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//*[contains(., 'login or register')]"))).click()
    
  • 注意:您必须添加以下导入:

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