有时候大家在爬虫的时候会遇到要登录的情况,如果不登录则爬不到自己想要的东西,这里以博客园为例,here we go~~
首先简单的介绍一下selenium和phantomJS:
selenium是一款测试工具,能够模拟用户对浏览器进行操作,
phantomJS是一款轻便式浏览器,其没有界面并且功能相对简单,因此速度上会比较快速。
说到这大家应该明白selenium+phantomJS如何实现登录破解了,对,就是模拟人工操作。
我们现看一下博客园的登录界面:https://passport.cnblogs.com/user/signin?ReturnUrl=https%3A%2F%2Fwww.cnblogs.com%2F
找到这些元素所在的点,填写账号密码,并且点击登录按钮,之后等待一段时间,因为页面加载需要时间,之后就可以爬取登陆后的界面:
话不多说,直接上代码:
package com.eversec.crawler; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.phantomjs.PhantomJSDriver; import org.openqa.selenium.phantomjs.PhantomJSDriverService; import org.openqa.selenium.remote.DesiredCapabilities; import java.util.List; import java.util.concurrent.TimeUnit; /** * Created by tyx on 2017/9/14. * 通过selenium+phantomJS登录博客园 */ public class CnblogLogin { public static void main(String[] args) throws Exception{ DesiredCapabilities desiredCapabilities = new DesiredCapabilities(); //ssl证书支持 desiredCapabilities.setCapability("acceptSslCerts", true); //截屏支持 desiredCapabilities.setCapability("takesScreenshot", true); //css搜索支持 desiredCapabilities.setCapability("cssSelectorsEnabled", true); //js支持 desiredCapabilities.setJavascriptEnabled(true); //驱动支持 desiredCapabilities.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY,"D:\phantomjs-2.1.1-windows\phantomjs-2.1.1-windows\bin\phantomjs.exe"); //创建无界面浏览器对象 WebDriver webDriver = new PhantomJSDriver(desiredCapabilities); try { webDriver.get("https://passport.cnblogs.com/user/signin?ReturnUrl=https%3A%2F%2Fwww.cnblogs.com%2F"); WebElement usernameEle = webDriver.findElement(By.id("input1")); WebElement passwordEle = webDriver.findElement(By.id("input2")); // 设置账号密码 usernameEle.sendKeys(""); passwordEle.sendKeys(""); WebElement loginButtom = webDriver.findElement(By.id("signin")); loginButtom.click(); webDriver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); List<WebElement> elements = webDriver.findElements(By.xpath("//a[@class='titlelnk']")); for (WebElement element : elements){ System.out.println(element.getText()); } }catch (Exception e){ e.printStackTrace(); }finally { webDriver.close(); webDriver.quit(); } } }
运行后结果如下:
由此实现对博客园登录的破解
欢迎大家来交流爬虫方面的经验