java使用Selenium完成boss直聘自动打招呼脚本

时间:2025-04-08 10:10:05
import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.interactions.Actions; import java.util.List; public class Main { static String msg = "您好,我有4年的工作经验,感觉和贵公司的岗位要求比较匹配,希望能进一步沟通下\n" + "本人目前是离职状态,一周内可以到岗\n" + "详情请查看我的简历,期望你的回复,谢谢您!"; static Integer num = 0; public static void main(String[] args) throws Exception { // 谷歌驱动 ChromeOptions options = new ChromeOptions(); // 允许所有请求 options.addArguments("--remote-allow-origins=*"); WebDriver webDriver = new ChromeDriver(options); // 打开登录页面 webDriver.get("/web/user"); // 用户需要在这两分钟内完成登录打开岗位查询页面 int time = 0; int timeOut = 1000 * 60 * 2; while (time < timeOut) { Thread.sleep(1000); time += 1000; System.out.println("程序将在" + (timeOut - time) / 1000 + "秒后开启自动沟通,请打开岗位页面"); } System.out.println("自动沟通开始..."); // 遍历10页 偷懒写死了 for (int page = 0; page < 10; page++) { // 获取这一页的工作岗位数量 int jobNum = webDriver.findElements(By.className("job-card-wrapper")).size(); for (int i = 0; i < jobNum; i++) { try { hi(webDriver, i); } catch (Exception e) { System.out.println("报错了:" + e.getMessage()); webDriver.navigate().refresh(); Thread.sleep(5000); } } try { // 下一页 webDriver.findElement(By.className("ui-icon-arrow-right")).click(); } catch (Exception e) { // 刷新页面重新尝试一次 webDriver.navigate().refresh(); Thread.sleep(5000); // 下一页 webDriver.findElement(By.className("ui-icon-arrow-right")).click(); } Thread.sleep(5000); } } public static void hi(WebDriver webDriver, int index) throws InterruptedException { // 回退页面后元素会刷新,需要重新获取一遍 List<WebElement> jobList = webDriver.findElements(By.className("job-card-wrapper")); for (int i = 0; i < jobList.size(); i++) { if (i == index) { try { // 使用Actions类进行悬浮 Actions actions = new Actions(webDriver); actions.moveToElement(jobList.get(i)).perform(); WebElement btn = jobList.get(i).findElement(By.className("start-chat-btn")); if (btn.getText().equals("继续沟通")) { break; } // 点击沟通按钮 btn.click(); num++; } catch (Exception e) { break; } Thread.sleep(1000); // 打招呼的消息 webDriver.findElement(By.className("chat-input")).sendKeys(msg); // 发送 webDriver.findElement(By.className("chat-input")).sendKeys(Keys.ENTER); System.out.println("沟通次数:" + num); Thread.sleep(1000); // 回退 webDriver.navigate().back(); Thread.sleep(2000); break; } } } }