首页 > 解决方案 > 运行脚本时chromedriver无法点击,但可以在shell中

问题描述

当 Python 运行代码时,我通常在单击 Chromedriver 时遇到问题。此代码在脚本中使用:

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

driver.get("https://www.marktplaats.nl/")
cook_button = WebDriverWait(driver, 15).until(EC.element_to_be_clickable((By.XPATH, "//form[@method='post']/input[@type='submit']"))).click()



它只是超时给出“NoSuchElementException”。但是,如果我将这些行手动放入 Shell 中,它会像往常一样单击。值得一提的是,我使用的是最新的 2.40 Chromedriver 和 Chrome v67。无头运行它没有任何区别。



编辑
该程序实际上在第三个命令之后中断,因为它试图找到一个不存在的元素,因为点击没有完成

driver.get(master_link) # get the first page
wait_by_class("search-results-table")


page_2_el = driver.find_element_by_xpath("//span[@id='pagination-pages']/a[contains(@data-ga-track-event, 'gination')]")


所以,page_2_el 命令给出了这个异常,但只是因为之前的点击没有成功完成,以删除关于 cookie 的警告。
而且我确信 xpath 搜索很好,因为它在 Firefox 中与 geckodriver 一起运行,但不会在这里与 Chromedriver 一起运行。



EDIT2
在此处查看该错误的视频https://streamable.com/tv7w4
注意它是如何退缩的,看看它何时在“单击前”和“单击后”在控制台上写入



解决方案已
更换

cook_button = WebDriverWait(driver, 15).until(EC.element_to_be_clickable((By.XPATH, "//form[@method='post']/input[@type='submit']"))).click()


N_click_attempts = 0
while 1:
    if N_click_attempts == 10:
        print "Something is wrong. "
        break
    print "Try to click."
    N_click_attempts = N_click_attempts+1
    try:
        cook_button = WebDriverWait(driver, 15).until(EC.element_to_be_clickable((By.XPATH, "//form[@method='post']/input[@type='submit']"))).click()
        time.sleep(2.0)
    except:
        time.sleep(2.0)
        break


看来现在点击完成了。我在脚本中有其他点击,它们与 element.click() 一起工作得很好,由于某种原因,这个有问题。

标签: python-2.7seleniumselenium-webdriverselenium-chromedriver

解决方案


您的路径是正确的,但我建议使用较小的路径:

//form/input[2]

关于NoSuchElementException- 你可以尝试添加一个暂停,等到元素加载并变得“可见” selenium。像这样:

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

driver.get("https://www.marktplaats.nl/")
cook_button = WebDriverWait(driver, 15).until(EC.element_to_be_clickable((By.XPATH, "//form[@method='post']/input[@type='submit']"))).click()
time.sleep(5) # wait 5 seconds until DOM will reload

根据问题中的编辑,我建议time.sleep(5)在单击按钮后添加。并且出于同样的原因,因为单击整个DOM重新加载后,selenium应该等到重新加载完成。在我的电脑上,完全重新加载DOM.


推荐阅读