selenium如何高亮某元素和操作隐藏的内容

高亮元素的思路是:

1.找到要高亮的元素

2.对该元素执行js,更改style达到高亮效果。

操作隐藏的内容思路:

1.可以用Actions的moveToElement,使鼠标悬停在触发隐藏内容的元素上。

2.也可以用js点击触发隐藏内容的元素

下面是具体的代码:

 

复制代码
package com.test;

import java.sql.Driver;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

import bsh.commands.dir;

/** 
 * @author QiaoJiafei 
 * @version 创建时间:2016年3月25日 下午3:00:31 
 * 类说明 
 */
public class TestHighLight {
    static WebDriver driver;
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        driver = new ChromeDriver();
        driver.manage().window().maximize();
        driver.get("http://www.zhihu.com/#signin");
        driver.findElement(By.name("account")).sendKeys("XXX@163.com");
        driver.findElement(By.name("password")).sendKeys("XXX");
        WebElement login = driver.findElement(By.xpath("//*//button[text()='登录']"));
        highl(driver, login);
        login.click();
        
        WebDriverWait wait = new WebDriverWait(driver, 10);
        WebElement element =wait.until(new ExpectedCondition<WebElement>() {

            @Override
            public WebElement apply(WebDriver dr) {
                // TODO Auto-generated method stub
                return dr.findElement(By.xpath("//*//span[text()='乔叶叶']"));
            }});
        
        /*
         * 使用js实现点击目标,出现隐藏元素
        String js = "document.getElementsByClassName(\"name\")[0].click()";
        ((JavascriptExecutor)driver).executeScript(js);
        */
        
        Actions action = new Actions(driver);
        action.moveToElement(element).perform();
        
        WebElement sixinElement = driver.findElement(By.id(":2"));//*[@id=":2"]
        highl(driver, sixinElement);
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        sixinElement.click();

        driver.quit();
        
    }
    
/*高亮显示*/
static void highl(WebDriver dr, WebElement we) { ((JavascriptExecutor)dr).executeScript("arguments[0].style.border=\"5px solid red\"", we); } }
复制代码

可以看下效果,把登录按钮高亮显示,因为知乎加载主页太慢,后面的操作隐藏元素的效果没有截图。

posted on   乔叶叶  阅读(1614)  评论(0编辑  收藏  举报

编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示