转载 

python selenium chrome 控制浏览器滚动条缓慢下拉到最底

分类:python,selenium    713人阅读    IT小君  2021-09-03 22:59

用selenium 爬取网站数据,有些网站的的数据是ajax动态加载,要缓慢分段下拉才可以获取到数据,如果连续用执行js语句'window.scrollTo(0,document.body.scrollHeight)'

会导致浏览器迅速直接拉到底,中间遗失数据。
代码实现思路:
首先获取当前窗口总高度
然后每次下拉100 像素,拉到最底;
只是如果又有新的页面内容加载,高度会变大,这时比较原高度与现在高度是否相同,如果不同,在每次100 像素下拉,直到没有新的内容加载。

这里以蘑菇街为例:蘑菇街如果直接拉到底他会什么数据页加载不了

import time
from selenium import webdriver

driver = webdriver.Chrome()
driver.get("https://www.mogu.com/")
time.sleep(1)

# 执行这段代码,会获取到当前窗口总高度
js = "return action=document.body.scrollHeight"
# 初始化现在滚动条所在高度为0
height = 0
# 当前窗口总高度
new_height = driver.execute_script(js)

while height < new_height:
    # 将滚动条调整至页面底部
    for i in range(height, new_height, 100):
        driver.execute_script('window.scrollTo(0, {})'.format(i))
        time.sleep(0.5)
    height = new_height
    time.sleep(2)
    new_height = driver.execute_script(js)
driver.quit()

把代码封装到函数复用

import time

def scroll_to_bottom(driver):
	js = "return action=document.body.scrollHeight"
	# 初始化现在滚动条所在高度为0
	height = 0
	# 当前窗口总高度
	new_height = driver.execute_script(js)

	while height < new_height:
    	# 将滚动条调整至页面底部
    	for i in range(height, new_height, 100):
        	driver.execute_script('window.scrollTo(0, {})'.format(i))
        	time.sleep(0.5)
    	height = new_height
    	time.sleep(2)
    	new_height = driver.execute_script(js)
支付宝打赏 微信打赏

如果文章对你有帮助,欢迎点击上方按钮打赏作者

 工具推荐 更多»