python-2.7 - 运行脚本时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() 一起工作得很好,由于某种原因,这个有问题。
解决方案
您的路径是正确的,但我建议使用较小的路径:
//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
.
推荐阅读
- git - 我必须在合并之前压缩 git commit。但是,它已合并到 master 分支,如何取消合并,压缩它们并再次合并?
- angular - Angular Jest 测试打开 MatDialog 的组件,该组件引用已发布库中的组件
- python - SQLAlchemy - 自定义声明基类中的自引用多对多关系
- python - Plotly Sankey 图,对齐节点
- vue.js - 将插槽内容提升一级
- azure - AKS 集群 | 查询可用的提供程序包失败 | hashcorp 的正确版本
- bash - 来自自定义函数的 echo 调用的 bash shell 问题
- python - 我一直在学习如何使用 Django,我正在尝试在 python shell 中创建对象,但是命令“python manage.py shell”对我不起作用
- c# - 在 C# 中创建方波(高低交替)
- ios - 底部导航栏仍显示在其他视图中