数据采集中,经常遇到动态加载的数据,我们经常使用selenium模拟浏览器操作,需要多次下拉刷新页面才能采集到所有的数据,就此总结了几种selenium操作下拉滚动条的几种方法
我这里演示的是Java版本的,使用chromedriver,当然你可以换成python或其他语言,浏览器用firefox或者phantomjs(无头浏览器),大部分都是适用的,不同浏览器有略微的差异。
初始化一个浏览器
首先要允许浏览器运行js脚本
DesiredCapabilities sCaps = new DesiredCapabilities();
sCaps.setJavascriptEnabled(true);
System.getProperties().setProperty("webdriver.chrome.driver", "D:/tool/chromedriver.exe"); WebDriver webDriver = new ChromeDriver(sCaps);
1.直接操作页面
#下拉到页面底部
((JavascriptExecutor) webDriver).executeScript("window.scrollTo(0,document.body.scrollHeight)"); #上拉到页面顶端 ((JavascriptExecutor) webDriver).executeScript("window.scrollTo(document.body.scrollHeight,0)");
或: