[置顶] selenium-java实现1688 cookies登录 和自动滑动验证码

/ Java / 0 条评论 / 1108 浏览

pom.xml

<dependency>
  <groupId>org.seleniumhq.selenium</groupId>
  <artifactId>selenium-java</artifactId>
  <version>3.141.59</version>
</dependency>

java代码

package com.jeesite.test;

import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;

import java.io.*;
import java.util.StringTokenizer;
import java.util.concurrent.TimeUnit;

/**
 * @author liuxin
 * @version 1.0
 * @date 2022/6/9 11:05
 */
public class web1688 {

    public static void main(String[] args) {
        String osName = System.getProperties().getProperty("os.name");
        if (osName.equalsIgnoreCase("Linux")) {
            System.out.println("running in Linux");
            System.setProperty("webdriver.chrome.driver", "src/main/resources/chromedriver_linux64/chromedriver");//chromederiver存放位置
        } else {
            System.out.println("don't running in Linux");
            System.setProperty("webdriver.chrome.driver", "src/main/resources/chromedriver_win32/chromedriver.exe");//chromederiver存放位置
        }
        ChromeDriver webDriver = null;
        try {
            ChromeOptions chromeOptions = new ChromeOptions(); //设置 chrome 的无头模式
            // chromeOptions.setHeadless(Boolean.TRUE);
            chromeOptions.setExperimentalOption("excludeSwitches", new String[]{"enable-automation"});
            chromeOptions.setExperimentalOption("useAutomationExtension", false);
            chromeOptions.addArguments("--disable-blink-features=AutomationControlled");
            chromeOptions.addArguments("--no-sandbox");//禁用沙箱
            chromeOptions.addArguments("--disable-dev-shm-usage");//禁用开发者shm
            //   chromeOptions.addArguments("--headless"); //无头浏览器,这样不会打开浏览器窗口
            // 启动一个 chrome 实例
            webDriver = new ChromeDriver(chromeOptions); //访问网址
            //  login(webDriver, "15******", "l******");
            // writerCookie(webDriver);
            String url = "https://detail.1688.com/offer/**********.html";
            webDriver.get(url);
            setCookies(webDriver);
            System.out.println("登录cookies:" + webDriver.manage().getCookies());
            slider(webDriver);
            Thread.sleep(3000);
            String body = webDriver.findElement(By.cssSelector("body")).getText();
            System.out.println("body:" + body);
            Thread.sleep(3000);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //退出chrome   taskkill /F /im chromedriver.exe
            if (webDriver != null) {
                webDriver.close();
                webDriver.quit();
            }
        }
    }

     /**
     * 出现滑块实现自动滑动验证
     * @param webDriver
     * @throws InterruptedException
     */
    public static void slider(ChromeDriver webDriver) throws InterruptedException {
        // ((JavascriptExecutor) webDriver).executeScript(js);
        Thread.sleep(3000);
        // webDriver.switchTo().frame(0); //need to switch to this frame before clicking the slider
        WebElement slider = webDriver.findElement(By.xpath("//*[@id=\"nc_1_n1z\"]"));
        if (slider != null && slider.isDisplayed()) {
            Actions move = new Actions(webDriver);
            Action action = (Action) move.dragAndDropBy(slider, 258, 0).build();
            action.perform();
        }
    }


    /**
     * 生成cookies
     *
     * @param webDriver
     * @throws IOException
     */
    public static void writerCookie(ChromeDriver webDriver) throws IOException {
        //成功登陆后增加如下代码
        File cookieFile = new File("D:\\cookie.txt");
        cookieFile.delete();
        cookieFile.createNewFile();
        FileWriter fileWriter = new FileWriter(cookieFile);
        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
        for (Cookie cookie : webDriver.manage().getCookies()) {
            bufferedWriter.write((cookie.getName() + ";" +
                    cookie.getValue()));
            bufferedWriter.newLine();
        }

//        for (Cookie cookie : webDriver.manage().getCookies()) {
//            bufferedWriter.write((cookie.getName() + ";" +
//                    cookie.getValue() + ";" +
//                    cookie.getDomain() + ";" +
//                    cookie.getPath() + ";" +
//                    cookie.getExpiry() + ";" +
//                    cookie.isSecure()));
//            bufferedWriter.newLine();
//        }
        bufferedWriter.flush();
        bufferedWriter.close();
        fileWriter.close();
    }

    /**
     * 设置cookies
     *
     * @param webDriver
     * @throws IOException
     */
    public static void setCookies(ChromeDriver webDriver) {
        webDriver.manage().deleteAllCookies();
        BufferedReader bufferedReader;
        try {
            File cookieFile = new File("D:\\cookie.txt");
            FileReader fileReader = new FileReader(cookieFile);
            bufferedReader = new BufferedReader(fileReader);
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                StringTokenizer stringTokenizer = new StringTokenizer(line, ";");
                while (stringTokenizer.hasMoreTokens()) {
                    String name = stringTokenizer.nextToken();
                    String value = stringTokenizer.nextToken();
                    Cookie cookie = new Cookie(name, value);
                    webDriver.manage().addCookie(cookie);
                }
            }
            webDriver.navigate().refresh();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
     
	 /**
     * 登录1688方法
     *
     * @param webDriver
     * @param username
     * @param password
     * @throws InterruptedException
     */
    public static void login(ChromeDriver webDriver, String username, String password) throws InterruptedException {
        webDriver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
        String baseUrl = "https://login.1688.com/";
        webDriver.get(baseUrl + "/member/signin.htm?spm=0.0.0.0.ijAHe8&Done=https%3A%2F%2Fs.1688.com%2Fcompany%2Fcompany_search.htm%3Fkeywords%3D%25B7%25FE%25D7%25B0%26button_click%3Dtop%26n%3Dy%26sortType%3Dpop%26pageSize%3D30%26offset%3D3%26beginPage%3D1");

        //  webDriver.switchTo().frame(0);
        webDriver.findElement(By.cssSelector(".password-login-tab-item")).click();
        //休息5秒
        Thread.sleep(5000);
        webDriver.findElement(By.id("fm-login-id")).clear();
        webDriver.findElement(By.id("fm-login-id")).sendKeys(username);
        webDriver.findElement(By.id("fm-login-password")).clear();
        webDriver.findElement(By.id("fm-login-password")).sendKeys(password);
        webDriver.findElement(By.cssSelector(".password-login")).click();
        //休息5秒
        Thread.sleep(5000);
    }
}


使用教程

首先需要下载 webDriver驱动 和你的谷歌浏览器匹配 先放开 用你的1688账户登录一次获取到登录cookies

 login(webDriver, "18******", "l******");
 writerCookie(webDriver);

然后 注释掉上面的方法,就可以实现自动登录和出现滑块自动验证的功能