You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Java WebDriver判断<article>标签是否存在并执行后续操作

Java WebDriver 判断
标签存在性及处理内部元素的实现指导

核心思路

要避免直接使用 findElement() 方法(找不到元素时会抛出 NoSuchElementException),推荐使用 findElements() 方法:它会返回一个元素列表,若列表为空则说明目标标签不存在;若列表非空,则可对内部元素进行处理。

具体实现步骤

  • 首先定位到父容器 div#patentResultList,缩小查找范围
  • 在该容器内查找所有 <article> 标签
  • 判断 <article> 标签列表是否非空:
    • 若存在:遍历每个 <article>,处理其内部的 div.search_section_title 和 div.search_basic_info
    • 若不存在:直接跳过后续处理步骤

完整代码示例

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.List;

public class PatentResultHandler {
    public static void main(String[] args) {
        // 初始化WebDriver(这里以Chrome为例)
        WebDriver driver = new ChromeDriver();
        
        try {
            // 假设已打开目标页面
            // 定位父容器
            WebElement resultContainer = driver.findElement(By.id("patentResultList"));
            
            // 在父容器内查找所有article标签
            List<WebElement> articleElements = resultContainer.findElements(By.tagName("article"));
            
            if (!articleElements.isEmpty()) {
                System.out.println("找到" + articleElements.size() + "个article标签,开始处理内部元素");
                
                for (WebElement article : articleElements) {
                    // 处理search_section_title
                    WebElement sectionTitle = article.findElement(By.className("search_section_title"));
                    String titleText = sectionTitle.getText().trim();
                    System.out.println("章节标题:" + titleText);
                    
                    // 处理search_basic_info
                    WebElement basicInfo = article.findElement(By.className("search_basic_info"));
                    String infoText = basicInfo.getText().trim();
                    System.out.println("基本信息:" + infoText);
                }
            } else {
                System.out.println("未找到article标签,跳过处理");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭浏览器
            driver.quit();
        }
    }
}

补充优化建议

  • 显式等待:如果页面是动态加载的,建议使用显式等待来确保父容器或 <article> 标签加载完成,避免因元素未加载导致的错误:
    import org.openqa.selenium.support.ui.WebDriverWait;
    import org.openqa.selenium.support.ui.ExpectedConditions;
    import java.time.Duration;
    
    // 等待父容器加载完成,最长等待10秒
    WebElement resultContainer = new WebDriverWait(driver, Duration.ofSeconds(10))
            .until(ExpectedConditions.presenceOfElementLocated(By.id("patentResultList")));
    
  • 异常处理:在处理内部 <div> 标签时,也可以用 findElements() 来判断是否存在,避免因某个内部元素缺失而中断整个流程。

内容的提问来源于stack exchange,提问作者Prabu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:54:31