22

誰か助けてくれませんか!

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);
        }
    }   
}
4

10 に答える 10

28

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に適したバージョン)、背景色を変更してハイライトを使用した場合、たとえば下の境界線のみを使用すると、はるかに短くなります。しかし、これは最も素晴らしいものです:)。

/*
 * 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];

質問、メモ、リクエスト、改善は大歓迎です!

于 2012-05-18T22:58:31.460 に答える
5

webdriver
でhighligh要素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"));)

テストでxpath" blaahblaah "を使用 してWebElementを強調表示します。

于 2014-03-06T10:53:08.057 に答える
3

JavaScript: 要素のXpath見つけて、その周りに境界線を描画します。

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);
    }
于 2015-08-25T12:03:43.523 に答える
1

以下のコードを使用して、javascriptexecuterを使用してWebドライバーのJavaコードを強調表示します。

//関数"flash"の下で呼び出しを行います

    public static void flash(WebElement element, WebDriver driver) {
        JavascriptExecutor js = ((JavascriptExecutor) driver);
        String bgcolor  = element.getCssValue("backgroundColor");
        for (int i = 0; i <  3; i++) {
            changeColor("rgb(0,200,0)", element, js);
            changeColor(bgcolor, element, js);
        }
    }
    public static void changeColor(String color, WebElement element,  JavascriptExecutor js) {
        js.executeScript("arguments[0].style.backgroundColor = '"+color+"'",  element);

        try {
            Thread.sleep(20);
        }  catch (InterruptedException e) {
        }
     }

お役に立てば幸いです:)

于 2012-06-01T05:41:37.650 に答える
1

セレンの元素を強調するためのコードは次のとおりです。最初にクラスを作成します。

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]);", element, "");
                Thread.sleep(500);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

    }

}

そして、あなたはこれを次のように呼ぶことができます:

driver.get(baseUrl);
            Thread.sleep(2000);
            WebElement lnkREGISTER = driver.findElement(By.linkText("REGISTER"));
            Miscellaneous.highLight(lnkREGISTER, driver);
            lnkREGISTER.click();
于 2017-11-10T13:05:38.480 に答える
0

WebDriverでこれを行う方法はわかりませんが、Selenium WebDriverには、すべてではないにしてもほとんどのRCAPIにアクセスできるクラスが存在するようです。WebDriverを使用して実際にこれを行う方法を知りません。

クラスWebDriverBackedSeleniumには、getEvalを含むことに慣れているRCAPIの多くが含まれているように見えます。

タイプのオブジェクトを作成するにはWebDriverBackedSelenium、テストサイトのベースURLに加えて、すでに使用しているドライバーを渡すだけです。

WebDriverBackedSelenium wdbs = new WebDriverBackedSelenium(driver, "http://www.google.com");
于 2012-05-18T22:53:31.063 に答える
0

これは私のために働いた。このスレッドで以前に送信されたコードを改善しました。

public static WebDriver HighlightElement(WebDriver driver, WebElement element){ 
    if (driver instanceof JavascriptExecutor) {
        ((JavascriptExecutor)driver).executeScript("arguments[0].style.border='3px solid red'", element);
    }
    return driver;
}
public static WebDriver UnhighlightElement(WebDriver driver, WebElement element){   
    if (driver instanceof JavascriptExecutor) {    
        ((JavascriptExecutor)driver).executeScript("arguments[0].style.border=''", element);
    }
    return driver;  
}

これらの2つの関数を1回呼び出してハイライトし、もう1回呼び出してハイライト解除します。

于 2018-03-05T15:56:36.757 に答える
0

ExtentReportをレポートツールとして使用しており、失敗したテストステップの画像をbase64形式で追加しています。これにより、出力レポートのテキストの直後に画像を表示できます。スクリーンショットを撮っていて、スクリーンショットでより見やすくするために要素を強調表示したい場合は、次の方法を使用して強調表示->スクリーンショット->強調表示を解除します。

private void highlightElement(WebElement elemToHighlight) {
    if (_driver instanceof JavascriptExecutor) {
        ((JavascriptExecutor) _driver).executeScript("arguments[0].style.border='3px solid red'", elem);
    }
}


public String addScreenshotToHTML(WebElement... elmsToHighlight) {
    String result;
    List<String> initStyle = new ArrayList<>();
    if (elmsToHighlight.length > 0) {
        for (WebElement elem : elmsToHighlight) {
            initStyle.add(elem.getCssValue("border"));
            highlightElement(elem);
        }
    }
    String screenshot = ((TakesScreenshot) _driver).getScreenshotAs(OutputType.BASE64);
    // NOTE: add the <img> tag content between the <a> tags with the Base64 image
    // <a href='" + filePath + "' target='_blank'></a>
    result = "<img onclick='(function(){var image=new Image();image.src=\"data:image/png;base64," + screenshot
            + "\";var w=window.open(\"\");w.document.write(image.outerHTML);})()' style='width:400px; cursor:pointer;' src='data:image/png;base64,"
            + screenshot + "'>";
    if (elmsToHighlight.length > 0) {
        for (WebElement elem : elmsToHighlight) {
            jsExec().executeScript("arguments[0].style.border='" + initStyle.get(0) + "'", elem);
            initStyle.remove(0);
        }
    }
    return result;
}

お役に立てば幸い

于 2020-03-05T11:34:14.660 に答える
0

要素を強調表示するには、次のように使用できます。

JavascriptExecutor js =(JavascriptExecutor)driver;
js.executeScript("arguments[0].style.border='5px dotted yellow'", element);
于 2020-07-01T14:57:34.923 に答える
-1
public class JavaExecutor {

public static void highlighElement(WebDriver driver,WebElement element)
{
    JavascriptExecutor js=(JavascriptExecutor)driver; 
    js.executeScript("arguments[0].setAttribute('style', 'background: yellow; border: 2px solid red;');", element);

    try 
    {
    Thread.sleep(1000);
    } 
    catch (InterruptedException e) {

    System.out.println(e.getMessage());
    } 

    js.executeScript("arguments[0].setAttribute('style','border: solid 2px white');", element); 

    }
}
于 2017-08-03T12:49:20.013 に答える