11.selenium应对懒加载

selenium可以操控浏览器来访问网页,但一些网站对此的反爬策略是使用网页懒加载,有的是图片懒加载,有的是网站信息懒加载。像百度图片,微博,开源中国等网站。
对于一般网站,使用代码直接滑动到窗口底部,就会有信息源源不断的加载下来,代码如下:

from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.get("https://cuiqingcai.com/")
time.sleep(3)
for i in range(4):
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight); var lenOfPage=document.body.scrollHeight; return lenOfPage;")
    time.sleep(3)
driver.close()

但有的网站必须有短暂时间的缓冲,直接跳转到底部就不会再有信息加载下来了。像这位大神的网站(https://cuiqingcai.com/)
这时就需要让滚动条向上滚动一下,然后再向下滚动。代码如下,这个可以应对绝大多数懒加载。

# coding:utf-8
from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.get("https://cuiqingcai.com/")
time.sleep(3)
# 创建一个列表,用于记录每一次拖动滚动条后页面的最大高度
All_Window_Height = []
# 当前页面的最大高度加入列表
All_Window_Height.append(driver.execute_script("return document.body.scrollHeight;"))
while True:
    # 执行拖动滚动条操作
    driver.execute_script("scroll(0,100000)")
    time.sleep(3)
    #获得窗口一半的高度
    halfheight = int(All_Window_Height[-1])/2
    print("一半的高度是{0}".format(halfheight))
    driver.execute_script("scroll(0,{0})".format(halfheight))
    time.sleep(3)
    driver.execute_script("scroll(0,100000)")
    time.sleep(3)
    check_height = driver.execute_script("return document.body.scrollHeight;")
    # 判断拖动滚动条后的最大高度与上一次的最大高度的大小,相等表明到了最底部
    print(check_height)
    if check_height == All_Window_Height[-1]:
        break
    else:
        # 如果不想等,将当前页面最大高度加入列表。
        All_Window_Height.append(check_height)
print(len(All_Window_Height))
driver.close()

你可能感兴趣的:(11.selenium应对懒加载)