Jsoup无法获取指定span标签id或class对应值的问题求助
问题原因
目标网站的互动量数据是JavaScript动态加载的,Jsoup仅能获取页面初始的静态HTML,此时<span class="js-summary-whole-engagement">内只有加载动画(<i class="fas fa-spinner fa-spin"></i>),实际互动数值还未填充,因此直接用Jsoup解析无法得到目标数据。
解决方案
方案1:使用支持JavaScript渲染的工具(如Selenium)
Selenium可模拟真实浏览器行为,等待页面JS执行完成后再抓取数据,步骤如下:
依赖准备
若使用Maven,先添加Selenium依赖:
<dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>4.15.0</version> </dependency>
同时下载对应浏览器的驱动(如ChromeDriver),可配置到环境变量或在代码中指定路径。
示例代码
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import java.time.Duration; public class InstagramEngagementScraper { public static void main(String[] args) { String accountUsername = "officialrickastley"; String url = "https://analisa.io/profile/" + accountUsername; // 初始化ChromeDriver,若驱动不在环境变量,需添加:System.setProperty("webdriver.chrome.driver", "你的驱动路径"); WebDriver driver = new ChromeDriver(); driver.get(url); // 等待目标元素加载完成,最长等待10秒 WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); WebElement engagementElement = wait.until( ExpectedConditions.presenceOfElementLocated(By.className("js-summary-whole-engagement")) ); // 获取互动量文本 String engagementText = engagementElement.getText(); System.out.println("平均互动量:" + engagementText); // 关闭浏览器 driver.quit(); } }
方案2:直接调用网站的API接口(更高效)
通过浏览器开发者工具的「Network」面板,可找到网站加载互动数据的后台API接口,直接请求接口获取JSON数据,比抓取页面更稳定高效:
- 打开目标页面,按F12打开开发者工具
- 切换到「Network」标签,刷新页面,过滤「XHR」请求
- 查找包含互动数据的请求(如含
engagement或profile的接口) - 复制接口URL,用Jsoup或HttpURLConnection请求并解析JSON
示例(需替换为实际接口)
import org.jsoup.Jsoup; import com.google.gson.JsonObject; import com.google.gson.JsonParser; public class ApiScraper { public static void main(String[] args) throws Exception { // 示例URL,需替换为实际找到的API接口 String apiUrl = "https://analisa.io/api/profile/officialrickastley/engagement"; String jsonResponse = Jsoup.connect(apiUrl) .userAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36") .ignoreContentType(true) // 忽略HTML类型检查,适配JSON响应 .execute() .body(); // 解析JSON数据 JsonObject json = JsonParser.parseString(jsonResponse).getAsJsonObject(); String engagement = json.get("whole_engagement").getAsString(); System.out.println("平均互动量:" + engagement); } }
注:需添加Gson依赖用于JSON解析,或使用其他JSON解析库。
注意事项
- 使用Selenium时,需保证浏览器版本与驱动版本匹配,避免兼容性问题
- 调用API时,需注意接口的请求头、参数是否需要验证,部分网站有反爬机制,需模拟真实请求的Headers
- 确保抓取行为符合网站的「Robots协议」和使用条款,规避法律风险
内容的提问来源于stack exchange,提问作者KingLavaCactus
相关产品推荐
相关产品推荐

