我需要点击DOM中的元素,但它们不会显示在浏览器页面上,除非我向下滚动到页面底部才能看到它。
我有更好的方法吗?
程序将失败并显示“消息:未知错误:元素在点上无法点击”而没有行scroll_browser(driver)
,在点击之前向下滚动就可以了。
import time
from selenium import webdriver
def scroll_browser(driver, destination_height=None):
# Get scroll height
if not destination_height:
destination_height = driver.execute_script("return document.body.scrollHeight")
while True:
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
new_height = driver.execute_script("return document.body.scrollHeight")
if new_height == destination_height:
break
destination_height = new_height
if __name__ == '__main__':
driver = webdriver.Chrome()
driver.get('https://wikimediafoundation.org/wiki/Home')
time.sleep(2)
link = '//a[text()="Terms of Use"]'
time.sleep(2)
#scroll_browser(driver)
driver.find_element_by_xpath(link).click()
time.sleep(2)
driver.close()
答案 0 :(得分:1)
尝试使用以下代码滚动到所需元素:
if __name__ == '__main__':
driver = webdriver.Chrome()
driver.get('https://wikimediafoundation.org/wiki/Home')
link = driver.find_element_by_link_text('Terms of Use')
driver.execute_script('arguments[0].scrollIntoView();', link)
link.click()
driver.close()