无法选中带有硒的复选框

时间:2019-06-06 06:05:51

标签: python-3.x selenium xpath css-selectors webdriverwait

我尝试抓取网站,需要选中一些复选框。

xpath = driver.find_element_by_xpath

for i in range(20):
    time.sleep(0.5)
    try:
        xpath("//*[@id='pub_check_sort3_0']").click()
        # checkbox = xpath("//*[@id='pub_check_sort3_0']")
        # driver.execute("arguments[0].click();",checkbox)
        break
    except NoSuchElementException as e:
        print('retry')
        time.sleep(1)
    else:
        raise e

这些是我尝试单击复选框但仍然无法单击该复选框的代码。另外,我不仅尝试了xpath值,还尝试了id和class。

<li class="general">
  <span class="fCheck">
    <input onclick="checkAction(this)" class="selectPL" type="checkbox" id="pub_check_sort3_0" value="025001">
     <label for="pub_check_sort3_0"></label>Academic Journal (1,505)</span></li>

这些是复选框的HTML代码,以下是xpath     // * [@ id =“ pub_check_sort3_0”]

Traceback (most recent call last):
  File "/Users/chanhee.kang/Desktop/DBpia/db_sel.py", line 37, in     <module>
    xpath("//*[@id='pub_check_sort3_0']").click()
  File "/Users/chanhee.kang/anaconda3/lib/python3.7/site-    packages/selenium/webdriver/remote/webelement.py", line 80, in click
    self._execute(Command.CLICK_ELEMENT)
  File "/Users/chanhee.kang/anaconda3/lib/python3.7/site-    packages/selenium/webdriver/remote/webelement.py", line 633, in     _execute
    return self._parent.execute(command, params)
  File "/Users/chanhee.kang/anaconda3/lib/python3.7/site-    packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "/Users/chanhee.kang/anaconda3/lib/python3.7/site-    packages/selenium/webdriver/remote/errorhandler.py", line 242, in     check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.ElementClickInterceptedException:     Message: element click intercepted: Element <input     onclick="checkAction(this)" class="selectPL" type="checkbox"     id="pub_check_sort3_0" value="025001"> is not clickable at point (73,     555). Other element would receive the click: <div class="filterGroup     eToggleSection">...</div>
  (Session info: chrome=74.0.3729.169)
  (Driver info: chromedriver=74.0.3729.6     (255758eccf3d244491b8a1317aa76e1ce10d57e9-refs/branch-heads/3729@{#29}),platform=Mac OS X 10.14.0 x86_64)

这些是我得到的错误。

1 个答案:

答案 0 :(得分:0)

要在所需元素上click(),必须诱使 WebDriverWait 使元素可点击,并且可以使用以下任一解决方案:

  • 使用CSS_SELECTOR

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "li.general label[for='pub_check_sort3_0']"))).click()
    
  • 使用XPATH

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//li[@class='general']//label[@for='pub_check_sort3_0']"))).click()
    
  • 注意:您必须添加以下导入:

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