登錄獲取token 可以說是爬蟲里面最難的點脓规,其他的只要能在瀏覽器上顯示的都可以用http工具獲取侨舆。只要稍微有點安全意識的網(wǎng)站登錄都比較復(fù)雜绢陌,JS混淆甚至可能密碼加密等等操作。
工具準(zhǔn)備
1脐湾、selenium 依賴添加。
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.141.59</version>
</dependency>
2愁铺、谷歌瀏覽器驅(qū)動闻鉴。驅(qū)動下載-》http://npm.taobao.org/mirrors/chromedrive 或者
https://chromedriver.storage.googleapis.com/index.html?path=75.0.3770.140/
3孟岛、本地電腦安裝谷歌瀏覽器,(其他瀏覽器也可以渠羞,需要下載對應(yīng)其他的驅(qū)動程序)
編碼爆破獲取token
package cn.harsons.crawling.crawling.reptile;
import lombok.extern.slf4j.Slf4j;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Set;
import java.util.stream.Collectors;
/**
* @author liyabin
* @date 2020/3/20 0020
*/
@Slf4j
@Component
public class TokenHander {
@Autowired
private Config config;
public String token() throws Exception {
//設(shè)置本地chrome driver地址 這里是你下載的谷歌瀏覽器 驅(qū)動路徑次询。
System.setProperty ("webdriver.chrome.driver", config.getDrivePath ());
//創(chuàng)建無Chrome無頭參數(shù)
ChromeOptions chromeOptions = new ChromeOptions ();
chromeOptions.addArguments ("-headless");
//創(chuàng)建Drive實例
WebDriver driver = new ChromeDriver (chromeOptions);
// 打開網(wǎng)站
driver.get (config.getLoginUrl ());
String currentUrl = driver.getCurrentUrl ();
log.info ("當(dāng)前連接" + currentUrl);
// 獲取瀏覽器頁面上的節(jié)點 類似 document.getElementById()
//拿到用戶名 和密碼的輸入框句柄
WebElement userName = driver.findElement (By.id ("userName"));
WebElement password = driver.findElement (By.id ("password"));
//向用戶名和密碼輸入框中寫入值
userName.sendKeys (config.getUserName ());
password.sendKeys (config.getPassword ());
// 拿到登錄按鈕的句柄
WebElement login_button = driver.findElement (By.className ("btn-submit"));
// 模擬點擊登錄
login_button.click ();
currentUrl = driver.getCurrentUrl ();
log.info ("當(dāng)前連接" + currentUrl);
// 拿到cookie 信息
Set<Cookie> cookies = driver.manage ().getCookies ();
return cookies.stream ().map (entity -> entity.getName () + "=" + entity.getValue ()).collect (Collectors.joining (";"));
}
}