在运行时期间突出显示WebDriver中的元素

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在运行时期间突出显示WebDriver中的元素相关的知识,希望对你有一定的参考价值。

有人可以帮忙!

如何在WebDriver的测试执行期间突出显示以下类中的所有Web元素?使用Selenium RC,它非常直接但是使用WebDriver我很挣扎。

如果有人可以请我提供一些我可以尝试的代码,我将不胜感激,这些代码也适合下面的课程 - 对不起,我的Java技能并不是那么好。

package hisScripts;
import java.util.concurrent.TimeUnit;
import org.testng.annotations.*;
import org.testng.Assert;
import static org.testng.Assert.fail;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.interactions.Actions;


public class R_LHAS_Only_Account_Verification extends HIS_Login_Logout{
    public WebDriver driver;
    public String baseUrl;
    public int exeMonth;
    private StringBuffer verificationErrors = new StringBuffer();

    @BeforeClass
    @Parameters ({"browser1", "url", "executionMonth"})
    public void setUp(String browser1, String url, int executionMonth) throws Exception {
        exeMonth = executionMonth;
        baseUrl = url;

        if (browser1.equals("FF")) {
            driver = new FirefoxDriver();
        } else if (browser1.equals("IE")){
            driver = new InternetExplorerDriver();
        }       
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);    
    }       

    @Test
    public void R_LHAS_Reports() throws Exception {
        R_LHAS_Only_Login(baseUrl, driver);
        Assert.assertEquals("Kingston upon Thames (RB)", driver.findElement(By.xpath("//html/body/div[9]/div/div[3]/div/div/div")).getText());
        Assert.assertEquals("Average price", driver.findElement(By.xpath("//table[@id='tableId']/tbody/tr/td")).getText());
        Assert.assertEquals("% price change", driver.findElement(By.xpath("//table[@id='tableId']/tbody/tr[2]/td")).getText());
        Assert.assertEquals("Lower quartile price", driver.findElement(By.xpath("//table[@id='tableId']/tbody/tr[3]/td")).getText());
        Assert.assertEquals("Time to sell (weeks)", driver.findElement(By.xpath("//table[@id='tableId']/tbody/tr[4]/td")).getText());
        Assert.assertEquals("% asking price achieved", driver.findElement(By.xpath("//table[@id='tableId']/tbody/tr[5]/td")).getText());
        Assert.assertEquals("House price to earnings ratio", driver.findElement(By.xpath("//table[@id='tableId']/tbody/tr[6]/td")).getText());
        Assert.assertEquals("Cost of buying outright - LQ 2 bed £pw", driver.findElement(By.xpath("//table[@id='tableId']/tbody/tr[7]/td")).getText());
        Assert.assertEquals("Private rent 2 bed £pw", driver.findElement(By.xpath("//table[@id='tableId']/tbody/tr[8]/td")).getText());
        Assert.assertEquals("80% private rent 2 bed £pw", driver.findElement(By.xpath("//table[@id='tableId']/tbody/tr[9]/td")).getText());
        Assert.assertEquals("Social rent 2 bed £pw", driver.findElement(By.xpath("//table[@id='tableId']/tbody/tr[10]/td")).getText());                 
        R_LHAS_Only_Logout(baseUrl,driver);
    }

    @AfterClass(alwaysRun=true)
    public void tearDown() throws Exception {
        driver.quit();
        String verificationErrorString = verificationErrors.toString();
        if (! "".equals(verificationErrorString)) {
            fail(verificationErrorString);
        }
    }   
}
答案

WebDriver中无法做到这一点(截至v2.21.0)。您可以尝试使用经过调整的方法替换通常的findElement(By)方法,该方法使用javascript突出显示找到的元素:

// Draws a red border around the found element. Does not set it back anyhow.
public WebElement findElement(By by) {
    WebElement elem = driver.findElement(by);
    // draw a border around the found element
    if (driver instanceof JavascriptExecutor) {
        ((JavascriptExecutor)driver).executeScript("arguments[0].style.border='3px solid red'", elem);
    }
    return elem;
}

现在你有了这个想法,有一个改进版本,当找到并突出显示一个新元素时,它恢复最后一个元素的原始border

// assuming JS is enabled
private JavascriptExecutor js = (JavascriptExecutor)driver;
private WebElement lastElem = null;
private String lastBorder = null;

private static final String SCRIPT_GET_ELEMENT_BORDER;
private static final String SCRIPT_UNHIGHLIGHT_ELEMENT;

void highlightElement(WebElement elem) {
    unhighlightLast();

    // remember the new element
    lastElem = elem;
    lastBorder = (String)(js.executeScript(SCRIPT_GET_ELEMENT_BORDER, elem));
}

void unhighlightLast() {
    if (lastElem != null) {
        try {
            // if there already is a highlighted element, unhighlight it
            js.executeScript(SCRIPT_UNHIGHLIGHT_ELEMENT, lastElem, lastBorder);
        } catch (StaleElementReferenceException ignored) {
            // the page got reloaded, the element isn't there
        } finally {
            // element either restored or wasn't valid, nullify in both cases
            lastElem = null;
        }
    }
}

和脚本!我使用FileUtils.readFileToString()从文件加载它们。

SCRIPT_GET_ELEMENT_BORDER(IE friendly version taken from this site),如果通过改变背景颜色(例如,只有底部边框)使用突出显示,它会更短。但这是最好的:)。

/*
 * Returns all border properties of the specified element as String,
 * in order of "width style color" delimited by ';' (semicolon) in the form of:
 * 
 * "2px inset #000000;2px inset #000000;2px inset #000000;2px inset #000000"
 * "medium none #ccc;medium none #ccc;1px solid #e5e5e5;medium none #ccc"
 * etc.
 */
var elem = arguments[0]; 
if (elem.currentStyle) {
    // Branch for IE 6,7,8. No idea how this works on IE9, but the script
    // should take care of it.
    var style = elem.currentStyle;
    var border = style['borderTopWidth']
            + ' ' + style['borderTopStyle']
            + ' ' + style['borderTopColor']
            + ';' + style['borderRightWidth']
            + ' ' + style['borderRightStyle']
            + ' ' + style['borderRightColor']
            + ';' + style['borderBottomWidth']
            + ' ' + style['borderBottomStyle']
            + ' ' + style['borderBottomColor']
            + ';' + style['borderLeftWidth']
            + ' ' + style['borderLeftStyle']
            + ' ' + style['borderLeftColor'];
} else if (window.getComputedStyle) {
    // Branch for FF, Chrome, Opera
    var style = document.defaultView.getComputedStyle(elem);
    var border = style.getPropertyValue('border-top-width')
            + ' ' + style.getPropertyValue('border-top-style')
            + ' ' + style.getPropertyValue('border-top-color')
            + ';' + style.getPropertyValue('border-right-width')
            + ' ' + style.getPropertyValue('border-right-style')
            + ' ' + style.getPropertyValue('border-right-color')
            + ';' + style.getPropertyValue('border-bottom-width')
            + ' ' + style.getPropertyValue('border-bottom-style')
            + ' ' + style.getPropertyValue('border-bottom-color')
            + ';' + style.getPropertyValue('border-left-width')
            + ' ' + style.getPropertyValue('border-left-style')
            + ' ' + style.getPropertyValue('border-left-color');
}
// highlight the element
elem.style.border = '2px solid red';
return border;

SCRIPT_UNHIGHLIGHT_ELEMENT

var elem = arguments[0];
var borders = arguments[1].split(';');
elem.style.borderTop = borders[0];
elem.style.borderRight = borders[1];
elem.style.borderBottom = borders[2];
elem.style.borderLeft = borders[3];

欢迎提出任何问题,注意事项,要求和改进!

另一答案

在webdriver中 为高亮元素HighlightElement创建一个类

HighlightElement.java

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebElement;

import com.project.setup.WebDriverManager;

public class HighlightElement {

    public static void highlightElement(WebElement element) {
        for (int i = 0; i <2; i++) {
            JavascriptExecutor js = (JavascriptExecutor) WebDriverManager.driver;
            js.executeScript("arguments[0].setAttribute('style', arguments[1]);", element, "color: yellow; border: 2px solid yellow;");
            js.executeScript("arguments[0].setAttribute('style', arguments[1]);", element, "");
            }
        }
}

您可以使用

HighlightElement.highlightElement(driver.findElement(By.xpath("blaah blaah"));)

to highlight the WebElement with xpath "blaah blaah" in your test.
另一答案

JavaScript:查找Xpathelement并在其周围绘制边框,

使用styleObj.setProperty(CSS propertyName,CSS propertyValue,priority)方法。 element_node.style.setProperty ("background-color", "green", null);

在本网站上测试js-code:https://developer.chrome.com/devtools/docs/console

var xpath = '//html/body/div/main/article/nav';
if (document.evaluate){
var element_node = document.evaluate(xpath, window.document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null ).singleNodeValue;
element_node.style.setProperty ('border', '3px solid green', 'important');

alert('Working Fine in this browser version');
}else{
alert('document.evaluate is Not supported by Internet Explorer');
}

public static void drawBorder(WebDriver driver, String xpath){
        WebElement element_node = driver.findElement(By.xpath(xpath));
        JavascriptExecutor jse = (JavascriptExecutor) driver;
        jse.executeScript("arguments[0].style.border='3px solid red'", element_node);
    }
另一答案

这里是用于在selenium中突出显示元素的代码:首先创建一个类:

package com.demo.misc.function;

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

public class Miscellaneous 
{
    public static void highLight(WebElement element, WebDriver driver)
    {
        for (int i = 0; i <2; i++) 
        {
            try {
                JavascriptExecutor js = (JavascriptExecutor) driver;
                js.executeScript("arguments[0].setAttribute('style', arguments[1]);", element, "color: black; border: 4px solid red;");
                Thread.sleep(500);
                js.executeScript("arguments[0].setAttribute('style', arguments[1

以上是关于在运行时期间突出显示WebDriver中的元素的主要内容,如果未能解决你的问题,请参考以下文章

Webdriver.io。用CTRL突出显示多个元素,然后单击咖啡符号

如何使用 Resharper 准确找出哪个规则将语法突出显示应用于 VS2022 中的特定代码元素?

用 R 在图中突出显示一个时期

选择元素中的文本(类似于用鼠标突出显示)

选择元素中的文本(类似于用鼠标突出显示)

选择元素中的文本(类似于用鼠标突出显示)