javascript - 使用 python + selenium 单击按钮

标签 javascript python selenium cookies

我使用 python 中的 selenium 通过 chrome 访问名为 iens 的网站。我希望我的脚本单击“Volgende”(荷兰语中的“下一页”的意思),以移至下一页。但是,我收到以下错误消息:

selenium.common.exceptions.WebDriverException: Message: unknown error:
Element is not clickable at point (853, 667). Other element would 
receive the click: <div class="cookiePolicy-content">...</div>

我认为当 selenium 进入网站时弹出的 cookie 出了问题。到目前为止,我还不知道如何才能摆脱cookies。

到目前为止我的代码:

from selenium import webdriver

chrome_path = '/Users/username/Downloads/chromedriver'
driver = webdriver.Chrome(chrome_path)
driver.get('https://www.iens.nl/restaurant+utrecht')

link = driver.find_element_by_link_text("Volgende")
link.click()

这是网站:https://www.iens.nl/restaurant+utrecht

最佳答案

是的,这是由于底部的 cookie float 页脚造成的。 Selenium 会将您的按钮滚动到 View 中,但它没有意识到它需要将其滚动到 cookie float div 上方。

我建议单击 Cookie 消息上的关闭按钮,或者将元素从 Cookie 消息后面滚动出来。

要关闭 cookie,您需要单击“关闭”并等待它消失:

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


chrome_path = '/Users/username/Downloads/chromedriver'
driver = webdriver.Chrome(chrome_path)
driver.get('https://www.iens.nl/restaurant+utrecht')

# Wait for cookie message
close_icon = WebDriverWait(driver, 5, 0.25).until(ec.visibility_of_element_located([By.CSS_SELECTOR, '.cookiePolicy-close']))
close_icon.click()
# Wait for cookie message to disappear
WebDriverWait(driver, 5, 0.25).until(ec.invisibility_of_element_located([By.CSS_SELECTOR, '.cookiePolicy-close']))
link = driver.find_element_by_link_text("Volgende")
link.click()

要从 cookie 消息后面滚动元素:

编辑:看来此页面也有一个 float 顶部标题,因此您实际上也不能将其滚动到页面顶部...您需要将其从 cookie 消息后面滚动出来。

from selenium import webdriver

chrome_path = '/Users/username/Downloads/chromedriver'
driver = webdriver.Chrome(chrome_path)
driver.get('https://www.iens.nl/restaurant+utrecht')

link = driver.find_element_by_link_text("Volgende")
# Scroll to element as Selenium would
driver.execute_script('arguments[0].scrollIntoView(false);', link)
# Then scroll it up to get it out from behind the message
driver.execute_script('window.scrollBy(0, 200)')
link.click()

编辑:我已经确认这两个选项都有效

关于javascript - 使用 python + selenium 单击按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41019195/

相关文章:

javascript - Vue只渲染第一个自定义组件问题

javascript - 调用 javascript 对象值给我 'undefined'

python - 在 python 中捕获 HTTP 错误的响应正文

java - 尝试提取嵌套 iframe 的 src 属性时出现陈旧元素引用异常

java - 使用 Selenium IEDriverServer 的文本输入速度非常慢?

javascript - 如何预测 Promises 的异步性质

javascript - 在 JAVASCRIPT 中编写一个测验,返回可在 Netflix 上观看的电影

python - 重写管理 View 方法 - Django

python - 在 Flask-SQLAlchemy session 之外保存到数据库

c# - Selenium WebDriver IE 性能