用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)