这里通过使用随机数随机决定滚动距离。
from time import sleep
from selenium import webdriver
from selenium.webdriver import ChromeOptions
import random
def scroll(_browser):
temp_height = 0
scroll_height = 100
while True:
scroll_height += 1000*random.random()
# _browser.execute_script('window.scrollTo(0, document.body.scrollHeight)')
_browser.execute_script('window.scrollTo(0, '+str(scroll_height)+')')
check_height = _browser.execute_script(
"return document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;")
# 如果两者相等说明到底了
if check_height == temp_height:
break
temp_height = check_height
print(check_height)
sleep(2)
if __name__ == '__main__':
option = ChromeOptions()
option.add_experimental_option('excludeSwitches', ['enable-automation'])
browser = webdriver.Chrome(executable_path='chromedriver.exe', options=option)
try:
# 对指定的url发起请求
browser.get('https://www.runoob.com/python/python-strings.html')
sleep(1)
scroll(browser)
# 执行js,让滚轮向下滚动
except Exception as e:
print(e)
finally:
browser.quit()