今天接了这样一个需求,只给公众号的名字,要求获取这些公众号下发布的文章,找了大量资料大多都很老或不可行,干脆自己搞
思路:
1.使用selenium模拟浏览器登录(此步骤主要获取登录态)
2.获取公众号唯一标识(需要登陆态)
3.获取文章链接(需要第二步获取的标识 以及 登陆态)
4.使用Jsoup爬取即可
解释:为什么要模拟登陆呢?
回答:在微信公众平台上有一个按钮
文章编辑时有一个查询入口
这样就可以通过输入名称的方式可以查到所有文章啦
所以我们需要利用这个接口,但接口访问是需要登陆状态的
开搞!!!
序章:依赖引入
注:这里默认使用maven引入依赖,记得刷新依赖哦 -> 这个按钮
<!-- Selenium Java 依赖 -->
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.11.0</version>
</dependency>
<!-- WebDriverManager 依赖 -->
<dependency>
<groupId>io.github.bonigarcia</groupId>
<artifactId>webdrivermanager</artifactId>
<version>5.6.3</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
<version>5.2</version>
</dependency>
一、使用selenium模拟浏览器登录
selenium可以模拟浏览器行为,打开我们需要的网站,因此只需要模拟下它的行为不要被检测到即可,使得像是“人”在操作即可,这里依赖大家自己引入哈
public static void login() {
// 启用 Selenium 自动下载功能
WebDriverManager.chromedriver().setup();
ChromeOptions edgeOptions = new ChromeOptions();
edgeOptions.addArguments("--remote-allow-origins=*");//解决 403 出错问题
// 创建 ChromeDriver 实例
WebDriver driver = new ChromeDriver(edgeOptions);
try {
// 打开微信公众号登录页面
driver.get("http://mp.weixin.qq.com");
// 等待页面加载完成
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(30));
// 等待用户扫码登录(检测页面标题是否变化),2025/3 月的名字,后期可能会变
wait.until(ExpectedConditions.not(ExpectedConditions.titleIs("微信公众平台")));
// 获取登录后的 Cookie
Set<Cookie> cookies = driver.manage().getCookies();
StringBuilder cookieStr = new StringBuilder();
System.out.println("登录后的 Cookies:");
for (Cookie cookie : cookies) {
cookieStr.append(cookie.getName()).append("=").append(cookie.getValue()).append(";");
System.out.println(cookie.getName() + " = " + cookie.getValue());
}
// 获取 Token(假设 Token 在首页链接的 URL 中)
WebElement homeLink = driver.findElement(By.xpath("//a[@title='首页']"));
String homeUrl = homeLink.getAttribute("href");
String token="";
if (homeUrl != null && homeUrl.contains("token=")) {
token = homeUrl.split("token=")[1];
System.out.println("Token: " + token);
} else {
System.out.println("未找到 Token,请检查页面结构。");
}
//查询开始,获取到登录态后调用自己的方法,去查公众号的唯一标识
searchBiz(cookieStr,token);
} catch (TimeoutException e) {
System.out.println("登录超时,请检查是否成功扫码登录。");
} catch (NoSuchElementException e) {
System.out.println("未找到首页链接,页面结构可能已变化。");
} finally {
// 关闭浏览器
driver.quit();
}
}
更新中,有时间再写...