我试图让 Selenium 单击一个按钮,Selenium 必须滚动才能单击该按钮。但是发生的情况是,当 Selenium 向下滚动时,按钮位于粘性条后面,Selenium 单击粘性条而不是按钮。
我正在使用 Firefox webdriver。
我尝试了以下方法:
DesiredCapabilities.FIREFOX["elementScrollBehavior"] = 1
self.driver = webdriver.Firefox()
当我将 elementScrollBehavior 设置为 1 时,它根本不会滚动。
我怎样才能让 Selenium 正确向下滚动,这样按钮就不会出现在粘性栏后面?
-编辑-
DesiredCapabilities.FIREFOX["elementScrollBehavior"] = 1
现在可以用了,但是还是不能点击按钮。即使粘性条现在不会妨碍。
请您参考如下方法:
你可以这样实现:
driver = webdriver.Firefox()
driver.get("http://somewebpage.example")
time.sleep(5)
while True:
try:
# Edit this to how you're currently scrolling
driver.execute_script("window.scrollBy(0, 150);")
button = driver.find_element(By.XPATH, YOUR_BUTTON_XPATH)
button.click()
break
except WebDriverException:
driver.execute_script("window.scrollBy(0, -100);")
time.sleep(2)
如果您的脚本滚动到很远并抛出异常,它将捕获此错误并将页面向上滚动 100 像素。
这应该保证你的按钮被点击,它会不断地向下移动 50px 页面直到它找到它但是你可以实现你的正常滚动方式然后捕获 WebDriverException 并向上滚动几个像素数。
