<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.141.59</version>
</dependency>
package com.example.demo.util;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.springframework.util.StringUtils;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
public class Test {
public static ConcurrentHashMap<String, String> map = new ConcurrentHashMap<>();
public static void main(String[] args) {
System.err.println(getCookie("13100000000", "221.122.91.74:9401"));
}
public static String getCode(String mobile) {
return "349587";
}
public static String getCookie(String mobile, String proxyIpAndPort) {
System.setProperty("webdriver.chrome.driver", "D:/chromeDriver/chromedriver.exe");
ChromeOptions chromeOptions = new ChromeOptions();
if (StringUtils.isEmpty(proxyIpAndPort)) {
chromeOptions.addArguments("--headless", "no-sandbox", "--disable-gpu", "--start-maximized");
} else {
chromeOptions.addArguments("--headless", "no-sandbox", "--disable-gpu", "--start-maximized", "--proxy-server=" + proxyIpAndPort);
}
WebDriver driver = new ChromeDriver(chromeOptions);
String getCookie = null;
try {
driver.get("http://m.yangkeduo.com/login.html");
driver.findElement(By.className("phone-login")).click();
Thread.sleep(new Random().nextInt(100) + 200);
driver.findElement(By.id("user-mobile")).sendKeys(mobile);
Thread.sleep(new Random().nextInt(100) + 200);
driver.findElement(By.id("code-button")).click();
Thread.sleep(new Random().nextInt(50) + 99);
driver.findElement(By.id("input-code")).sendKeys(getCode(mobile));
Thread.sleep(new Random().nextInt(100) + 200);
WebElement element = driver.findElement(By.id("submit-button"));
element.sendKeys(Keys.ENTER);
Thread.sleep(new Random().nextInt(100) + 900);
Set<Cookie> cookies = driver.manage().getCookies();
Set<String> set = new HashSet<>();
for (Cookie cookie : cookies) {
String[] regex = cookie.toString().split(";");
for (String key : regex) {
String[] split = key.split("=");
if (split[0].equalsIgnoreCase("PDDAccessToken") || split[0].equalsIgnoreCase("api_uid")) {
set.add(key);
}
}
}
getCookie = String.join(";", set);
map.put(mobile, getCookie);
} catch (Exception e) {
e.printStackTrace();
} finally {
driver.close();
}
return getCookie;
}
}