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));
    }
}
相关推荐
喵手9 小时前
Python爬虫实战:针对天文历法网站(以 TimeandDate 或类似的静态历法页为例),构建高精度二十四节气天文数据采集器(附xlsx导出)!
爬虫·python·爬虫实战·零基础python爬虫教学·采集天文历法网站数据·构建二十四节气天文数据
喵手11 小时前
Python爬虫实战:采集博客园 Cnblogs文章标题、发布日期、标签以及HTML正文等(附 Markdown 文档格式预览)!
爬虫·python·爬虫实战·python爬虫工程化实战·零基础python爬虫教学·博客园文章采集·博客园文章采集转md格式
10岁的博客11 小时前
Libvio.link爬虫技术全解析
爬虫
2501_9481201513 小时前
大语言模型与爬虫技术融合的智能数据采集系统
人工智能·爬虫·语言模型
喵手15 小时前
Python爬虫实战:采集巨潮资讯网等上市公司公告数据,通过智能关键词匹配技术识别分红、回购、停牌等重要信息(附CSV导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·零基础python爬虫教学·采集巨潮资讯数据·智能匹配识别分红、回购等信息·csv导出+sqlite
泡泡以安15 小时前
Android 逆向实战:从零突破某电商 App 登录接口全参数加密
android·爬虫·安卓逆向
axinawang15 小时前
第9章 存储爬虫数据
爬虫
Data_Journal17 小时前
Scrapy vs. Crawlee —— 哪个更好?!
运维·人工智能·爬虫·媒体·社媒营销
深蓝电商API18 小时前
async/await与多进程结合的混合爬虫架构
爬虫·架构
Fleshy数模18 小时前
我的第一只Python爬虫:从Requests库到爬取整站新书
开发语言·爬虫·python