我正在学习如何使用硒,而且我一直在想弄清楚如何在网站中向下滚动以验证元素是否存在。
我尝试使用此问题中找到的方法 Scrolling to element using webdriver?
但是selenium不会向下滚动页面。相反,它会给我一个错误
" selenium.common.exceptions.NoSuchElementException:消息:无法找到元素:元素"
继承我正在使用的代码
moveToElement:
element = driver.find_element_by_xpath('xpath')
actions = ActionChains(driver)
actions.move_to_element(element).perform()
滚动浏览
element = driver.find_element_by_xpath('xpath')
driver.execute_script("arguments[1].scrollIntoView();", element)
整个代码:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
driver = webdriver.Firefox()
driver.get("https://www.linkedin.com/")
element =
driver.find_element_by_xpath('/html/body/div/main/div/div[1]/div/h1/img')
element = driver.find_element_by_xpath('//*[@id="login-email"]')
element.send_keys('')
element = driver.find_element_by_xpath('//*[@id="login-password"]')
element.send_keys('')
element = driver.find_element_by_xpath('//*[@id="login-submit"]')
element.click();
element = driver.find_element_by_xpath('')
actions = ActionChains(driver)
actions.move_to_element(element).perform()
答案 0 :(得分:0)
你的问题有两个方面
元素是否存在?
页面上可能存在元素[即。它是DOM的一部分]但它不能立即用于进一步的硒动作,因为它不可见[隐藏],它只在某些动作后才会显示,或者可能会在页面上滚动显示。
您的代码在此处抛出异常 -
element = driver.find_element_by_xpath('xpath')
WebDiver
无法使用提到的xpath
找到该元素。一旦解决了这个问题,你就可以向前推进下一部分了。
页面上是否显示元素?
解决上述问题后,您应该检查元素是否正在显示。如果它没有在滚动中显示和使用,那么您可以使用
之类的代码if !element.is_displayed():
driver.execute_script("arguments[1].scrollIntoView();", element)
使用Action Class进行非常特定的鼠标操作。
<强>更新: - 强>
如果你是使用延迟加载的应用程序,你想要找到的元素可以滚动,你可以尝试这样的事情 -
您必须导入例如 -
之类的异常from selenium.common.exceptions import NoSuchElementException
并创建新的递归函数,如果找不到元素,它将滚动,如下所示 -
def search_element():
try:
elem = driver.find_element_by_xpath("your")
return elem
except NosSuchElementException:
driver.execute_script("window.scrollTo(0,Math.max(document.documentElement.scrollHeight,document.body.scrollHeight,document.documentElement.clientHeight));")
search_element()
我不确定在这里找到元素的重复是个好主意,我也有一个naver在python上工作所以你需要了解语法
答案 1 :(得分:0)
Amm可能会有所帮助。只需发送页面向下键,如果你确定该元素肯定存在,那么这将有效
from selenium.webdriver.common.keys import Keys
from selenium.webdriver import ActionChains
import time
while True:
ActionChains(driver).send_keys(Keys.PAGE_DOWN).perform()
time.sleep(2) #2 seconds
try:
element = driver.find_element_by_xpath("your_element_xpath")
break
except:
continue