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));
    }
}
相关推荐
智航GIS7 小时前
10.4 Selenium:Web 自动化测试框架
前端·python·selenium·测试工具
廖圣平9 小时前
从零开始,福袋直播间脚本研究【三】《多进程执行selenium》
python·selenium·测试工具
我想吃烤肉肉17 小时前
Playwright中page.locator和Selenium中find_element区别
爬虫·python·测试工具·自动化
0思必得017 小时前
[Web自动化] Selenium基础介绍
前端·python·selenium·自动化·web自动化
测试199818 小时前
Web自动化测试入门
自动化测试·软件测试·python·功能测试·selenium·测试工具·测试用例
lbb 小魔仙18 小时前
【Python】零基础学 Python 爬虫:从原理到反爬,构建企业级爬虫系统
开发语言·爬虫·python
努力变大白19 小时前
借助AI零基础快速学会Python爬取网页信息-以天眼查爬虫为例
人工智能·爬虫·python
AC赳赳老秦21 小时前
Unity游戏开发实战指南:核心逻辑与场景构建详解
开发语言·spring boot·爬虫·搜索引擎·全文检索·lucene·deepseek
0思必得021 小时前
[Web自动化] Selenium简单使用
前端·python·selenium·自动化·web自动化