如何在Python中使用selenium“向下滚动”某些部分?

Noo*_*mer 3 python selenium scroll selenium-chromedriver selenium-webdriver

希望你很好,我正在尝试制作一个简单的脚本,但我被困在那里,我试图滚动列表以获取更多内容,但我无法向下滚动。任何人都知道这是如何完成的。

\n

这是我的代码:

\n
import selenium\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nfrom shutil import which\nimport time\nimport pandas as pd\nimport json\n# from fake_useragent import UserAgent\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\nfrom selenium.common.exceptions import TimeoutException\nchrome_path = which(\'chromedriver\')\ndriver = webdriver.Chrome(executable_path=chrome_path)\ndriver.maximize_window()\n\ndriver.get(\'http://mapaescolar.murciaeduca.es/mapaescolar/#\')\n\ndriver.find_element_by_xpath(\'//ul[@class="nav property-back-nav floating-box pull-right"]//button\').click()\ntime.sleep(3)\ndriver.find_element_by_xpath(\'//button[@ng-click="openCloseFilters()"]\').click()\ntime.sleep(3)\ndriver.find_element_by_xpath(\'//select[@title="Ense\xc3\xb1anza"]/option[1]\').click()\n\n\n\nelement = driver.find_element_by_xpath(\'//div[@id="container1"]\')\ndriver.execute_script("return arguments[0].scrollIntoView(true);", element)\n
Run Code Online (Sandbox Code Playgroud)\n

我想向下滚动的列表:

\n

这是我想要滚动的列表

\n

小智 6

因为滚动实际上是在一个元素内部,所以所有带有 window.js 的 javascript 命令。不管用。此外,该元素不可交互,因此按键也不适合。我建议使用scrollTo javascript执行器并设置一个变量,该变量将通过循环增加:

element = driver.find_element_by_xpath('//div[@id="container1"]')
time.sleep(10)

verical_ordinate = 100
for i in range(0, 50):
   print(verical_ordinate)
   driver.execute_script("arguments[0].scrollTop = arguments[1]", element, verical_ordinate)
   verical_ordinate += 100
   time.sleep(1)
Run Code Online (Sandbox Code Playgroud)

我已经用 chrome 进行了测试,所以它应该可以工作。

参考

https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTop