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));
    }
}
相关推荐
xmtxz4 分钟前
Burp Suite、爬虫、目录扫描工具实操深度总结
爬虫
yijianace34 分钟前
Python爬虫实战:BooksToScrape 多线程爬取与图片下载
开发语言·爬虫·python
深蓝电商API3 小时前
Playwright 多浏览器并发:同时操控 100 个 Chrome 实例
爬虫·playwright
数据知道14 小时前
斩断 `navigator` 前端:底层重写 UserAgent/Platform/Language 属性描述符
爬虫·数据采集·指纹浏览器·浏览器指纹
深蓝电商API20 小时前
Playwright深入浅出:从入门到企业级项目实战
爬虫·playwright
小白学大数据21 小时前
爬虫性能天花板:asyncio赋能 Aiohttp,并发提速 10 倍
开发语言·爬虫·数据分析
yijianace1 天前
Python爬虫实战:分页爬取 + 详情页采集 + CSV存储
前端·爬虫·python
yijianace1 天前
Python爬虫实战:ThreadPoolExecutor多线程采集书籍信息与图片下载
开发语言·爬虫·python
在放️1 天前
Python 爬虫 · bs4 模块基础
开发语言·爬虫·python
belong_my_offer1 天前
Python 数据采集完全指南 —— 从零开始掌握网络爬虫与文件读取
开发语言·爬虫·python