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

如何用Java+Selenium验证Expedia标签悬停时的下划线显示

验证Expedia顶部标签悬停下划线的Selenium实现方案

要验证Expedia首页顶部Stays、Flights等标签悬停时的黑色下划线,核心思路是模拟鼠标悬停后,检查元素(或其伪元素)的CSS样式是否符合下划线特征,以下是具体实现步骤和代码:

核心步骤

  • 初始化Selenium驱动,访问Expedia官网
  • 定位目标标签元素
  • 使用Actions类模拟鼠标悬停操作
  • 获取悬停后元素的CSS属性,验证是否存在黑色下划线样式

代码实现

基础版(检查元素自身CSS)

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.interactions.Actions;

public class ExpediaTabHoverTest {
    public static void main(String[] args) {
        WebDriver driver = new ChromeDriver();
        driver.manage().window().maximize();
        driver.get("https://www.expedia.com/");

        // 定义所有顶部标签的定位路径
        String[] tabXpaths = {
            "//a[@aria-label='Stays']",
            "//a[@aria-label='Flights']",
            "//a[@aria-label='Cars']",
            "//a[@aria-label='Packages']",
            "//a[@aria-label='Cruises']",
            "//a[@aria-label='Things to Do']"
        };

        Actions actions = new Actions(driver);

        for (String xpath : tabXpaths) {
            WebElement tab = driver.findElement(By.xpath(xpath));
            // 执行悬停
            actions.moveToElement(tab).perform();
            
            // 获取关键CSS属性:border-bottom或text-decoration
            String borderBottom = tab.getCssValue("border-bottom");
            String textDecoration = tab.getCssValue("text-decoration");

            // 验证黑色下划线(根据页面实际样式调整判断条件)
            boolean underlineExists = borderBottom.contains("1px solid rgb(0, 0, 0)") 
                                      || textDecoration.contains("underline");

            System.out.printf("标签 %s 悬停下划线验证:%s%n", 
                              tab.getText(), underlineExists ? "通过" : "失败");
        }

        driver.quit();
    }
}

进阶版(处理伪元素实现的下划线)

如果下划线是通过CSS伪元素(如:after/:before)实现的,需要用JavascriptExecutor获取伪元素样式:

import org.openqa.selenium.JavascriptExecutor;
// ... 其他导入同基础版

// 在悬停后添加以下代码获取伪元素样式
String pseudoBorder = (String) ((JavascriptExecutor) driver).executeScript(
    "return window.getComputedStyle(arguments[0], ':after').getPropertyValue('border-bottom');", tab);

boolean pseudoUnderlineExists = pseudoBorder.contains("1px solid rgb(0, 0, 0)");

注意事项

  • 元素定位方式可根据页面DOM结构调整(如用By.cssSelector替代By.xpath)
  • 实际判断条件需匹配Expedia页面的真实CSS值(可通过浏览器开发者工具查看悬停时的样式)
  • 若页面加载慢,可添加显式等待确保元素可交互:
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;

// 定位前添加等待
WebElement tab = new WebDriverWait(driver, 10)
    .until(ExpectedConditions.elementToBeClickable(By.xpath(xpath)));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 18:52:52