无法使用 Python 和 Selenium 单击没有任何文本的标签

Unable to click label that doesn't have any text using Python and Selenium

我正在尝试点击下面的标签。

标签html:

<div class="is-inline-block">
  <input id="entradas-checkbox-condiciones" type="checkbox" class="switch is-rounded is-small">
  <label style="padding-left:1rem;">

我试过使用以下代码点击标签:

WebDriverWait = wait

label1 = wait(self.driver, 10).until(EC.presence_of_all_elements_located((By.XPATH, "//*[@class = 'is-inline-block']")))[3]
label1.find_element_by_xpath('//label[style="padding-left:1rem;"]').click()

但是我收到以下错误:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element:

有人可以帮我写代码吗? 提前致谢。

定位并调用 on the clickable element instead of you need to induce WebDriverWait for the and you can use either of the following

  • 使用CSS_SELECTOR:

    WebDriverWait(self.driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.is-inline-block input.switch.is-rounded.is-small#entradas-checkbox-condiciones"))).click()
    
  • 使用 XPATH:

    WebDriverWait(self.driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='is-inline-block']//input[@class='switch is-rounded is-small' and @id='entradas-checkbox-condiciones']"))).click()
    
  • 注意:您必须添加以下导入:

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

参考资料

您可以在以下位置找到关于 的一些相关讨论: