无法通过Python中的Selenium单击复选框

时间:2014-12-30 14:01:47

标签: python selenium selenium-webdriver

为什么我无法通过Python中的Selenium点击页面https://realty.yandex.ru/add上的以下复选框?

enter image description here

import traceback

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


explicit_wait_timeout_secs = 10


def wait_for_element_presence(driver, find_type, web_element):
    return selenium.webdriver.support.ui.WebDriverWait(driver, explicit_wait_timeout_secs).until(EC.presence_of_element_located((find_type, web_element)))


def wait_for_element_clickable(driver, find_type, web_element):
    return selenium.webdriver.support.ui.WebDriverWait(driver, explicit_wait_timeout_secs).until(EC.element_to_be_clickable((find_type, web_element)))


try:
    driver = selenium.webdriver.Chrome()

    driver.get('https://realty.yandex.ru/add/')

    # element = wait_for_element_clickable(driver, By.NAME, 'lift')  # TimeoutException
    element = wait_for_element_presence(driver, By.NAME, 'lift')  # WebDriverException: Message: unknown error: Element is not clickable at point (203, 899). Other element would receive the click: <span class="checkbox__box">...</span>
    element.click()
except Exception:
    print('ERROR: \n' + traceback.format_exc())

try:
    driver.quit()
except Exception:
    pass

如果我试图等待&#34;可点击性&#34;这个元素,它给了我TimeoutException错误。如果我试图等待元素的存在,它会给我&#34;元素不可点击&#34;错误。

但是,我可以通过Javascript点击此复选框:

driver.execute_script("document.getElementsByName('lift')[0].click();")

它也适用于Firefox btw。

为什么呢?我究竟做错了什么?我该如何解决?

提前致谢。

2 个答案:

答案 0 :(得分:5)

您需要点击span标记,该标记是input标记的父级的父级name="lift"

element = driver.find_element_by_xpath('//span[span/input[@name="lift"]]')
element.click()

适用于Chrome和Firefox:

enter image description here

为安全起见,您还可以在点击之前scroll to an element

def scroll_element_into_view(driver, element):
    """Scroll element into view"""
    y = element.location['y']
    driver.execute_script('window.scrollTo(0, {0})'.format(y))

element = driver.find_element_by_xpath('//span[span/input[@name="lift"]]')
scroll_element_into_view(driver, element)
element.click()

答案 1 :(得分:0)

我们可以使用它来使用Javascript单击元素

element=driver.find_element(By.ID,"sdd")
driver.execute_script("arguments[0].click();", element) 

driver.execute_script("arguments[0].click();", driver.find_element(By.ID,"sdd"))