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));
    }
}
相关推荐
ZC跨境爬虫几秒前
批量爬取小说章节并优化排版(附完整可运行脚本)
前端·爬虫·python·自动化
AI_Claude_code1 小时前
ZLibrary访问困境方案二:DNS-over-HTTPS/TLS配置与隐私保护实践
爬虫·python·网络协议·http·网络安全·https·网络爬虫
小白学大数据3 小时前
告别复杂 XPath:DeepSeek+Python 爬虫快速实践
开发语言·爬虫·python·selenium
AI_Claude_code3 小时前
ZLibrary访问困境方案六:自建RSS/Calibre内容同步服务器的完整指南
运维·服务器·网络·爬虫·python·tcp/ip·http
AI_Claude_code3 小时前
安全与合规核心:匿名化、日志策略与法律风险规避
网络·爬虫·python·tcp/ip·安全·http·网络爬虫
专注API从业者14 小时前
淘宝商品详情 API 与爬虫技术的边界:合法接入与反爬策略的技术博弈
大数据·数据结构·数据库·爬虫
ZC跨境爬虫16 小时前
Scrapy工作空间搭建与目录结构解析:从初始化到基础配置全流程
前端·爬虫·python·scrapy·自动化
深蓝电商API17 小时前
分布式爬虫在海淘数据采集中的应用
爬虫·反向海淘
小白学大数据17 小时前
Scrapy 分布式爬虫:大规模采集汽车之家电车评论
开发语言·分布式·爬虫·scrapy
跨境麦香鱼17 小时前
Playwright vs Puppeteer:2026自动化任务与爬虫工具如何选?
运维·爬虫·自动化