selenium获取登录token

背景

新到一个需求需要用爬虫采集数据,但这个采购的系统登录做了加密,我也懒得研究前端代码了,于是考虑用selenium来获取用户token做处理。

下载webdriver

由于我开发机器使用的chorme,因此下载的chorme webdriver,地址如下:
webdriver

有一个坑爹的地方在于chorme会自动更新,而webdriver的版本必须跟chorme的版本匹配,因此生产环境我是安装的Chromium,它就不会自动更新了哈哈哈哈。

代码

java 复制代码
package com.spider;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URISyntaxException;

public class SyncDataTask {

    public String getAuthToken() throws InterruptedException, URISyntaxException, IOException {
    	//注意这里替换成你对应的地址 比如我的是/Users/xxxx/lib/chromedriver
        System.getProperties().setProperty("webdriver.chrome.driver", "替换成webdriver地址");

        ChromeOptions options = new ChromeOptions();
        options.addArguments("--disable-blink-features=AutomationControlled");
        //1、1解决403错误
        options.addArguments("--remote-allow-origins=*");
        //3、关闭左上方Chrome 正受到自动测试软件的控制的提示
        options.setExperimentalOption("useAutomationExtension", false);
        // 1.创建webdriver驱动
        WebDriver driver = new ChromeDriver(options);
        // 2.打开首页
        driver.get("https://xxxxx.com");
        Thread.sleep(1000);
        //输入账号密码
        driver.findElement(By.className("user-name")).sendKeys("account");
        driver.findElements(By.className("ant-input-lg")).get(1).sendKeys("password");
        //点击登录
        driver.findElement(By.className("login-refactoring-btn")).click();
        Thread.sleep(5000L);
        String token = getItemFromLocalStorage("token", driver);
        log.info("token:{}", token);
        driver.quit();
        return JSONObject.parseObject(token).getString("access_token");
    }

    public static String getItemFromLocalStorage(String key, WebDriver driver) {
        JavascriptExecutor js = ((JavascriptExecutor) driver);
        return (String) js.executeScript(String.format("return window.localStorage.getItem('%s');", key));
    }
}
相关推荐
_.Switch1 天前
东方财富股票数据JS逆向:secids字段和AES加密实战
开发语言·前端·javascript·网络·爬虫·python·ecmascript
码界奇点1 天前
基于Python的新浪微博数据爬虫系统设计与实现
数据库·爬虫·python·毕业设计·新浪微博·源代码管理
tang777891 天前
代理IP质量检测实战:Python实现IP可用性、延迟、匿名度自动测试脚本
大数据·爬虫·python·网络协议·tcp/ip
datascome2 天前
文章自动采集发布到Discuz网站技巧
经验分享·爬虫·数据采集·discuz·网站内容批量发布
亿牛云爬虫专家2 天前
Go爬虫进阶:如何优雅地在Colly框架中实现无缝代理切换?
爬虫·中间件·golang·爬虫代理·colly框架·代理切换·api提取
小白学大数据3 天前
Python 3.7 高并发爬虫:接口请求与页面解析并发处理
开发语言·爬虫·python
深蓝电商API3 天前
淘宝商品主图视频下载:从 API 返回值中提取视频 URL 并转码
爬虫·接口·api·淘宝api
测试19983 天前
Selenium自动化测试框架的搭建
自动化测试·软件测试·python·selenium·测试工具·职场和发展·测试用例