想要在页面源代码中出现的asser文本

时间:2015-08-10 11:35:28

标签: javascript selenium webdriver

我想断言某些文本是否存在于PageSource Code中,。

PageSource代码:

<script type="text/javascript">

    var rlSerial = '1057388';//Wanted to assert this text
    var rlAnid = 'I888pokerrussiaI';
    var rlFlag = '';
    var rlSearchTerm = '';
    var rlSearchEngine = '';
    var rlCurrency = '';
    var rlLang = 'en';
    var rlDl =  '';
    var rlCampaignId = '';
    var rlCountry = 'ind';
    var rlServerTime = '2015-08-10 10:37:53';
    var rlPid = '';
    var rlMkw = '';
    var MGbannerTag = '';
    var rlWtc  = '';
    var rlWtv  = '';

</script>

我使用了以下脚本,但它不起作用

Webdriver脚本:

driver.findElement(By.xpath("//*[@id='menu-item-154']/a")).click();
String Tournament=driver.findElement(By.xpath("//*[@id='text-31']/div/a/img")).getAttribute("outerHTML");
String VTournament=driver.findElement(By.xpath("//*[@id='tertiary']/div/div/div/p/a/img")).getAttribute("outerHTML");
Tournament.contains(Default_BannerName);
VTournament.contains(Default_VBannerName);
driver.findElement(By.xpath("//*[@id='text-31']/div/a/img")).click();
for (String winHandle : driver.getWindowHandles()) 
{
    driver.switchTo().window(winHandle); // switch focus of WebDriver to the next found window handle (that's your newly opened window)
    boolean b = driver.getPageSource().contains("var rlSerial = '1058358';");
    assertTrue(b);
}

请指导我

2 个答案:

答案 0 :(得分:1)

//Only way you can read a variable is using javascript
//with <code>executeScript</code> method as shown bellow.
private void test(){
    String script = "return rlSerial;";
    String value = (String) ((JavascriptExecutor)driver).executeScript(script);
    System.out.println(value);
    //Use assert here
}

答案 1 :(得分:0)

您可以遍历所有SCRIPT代码并搜索所需的文字。

List<WebElement> scriptTags = driver.findElements(By.tagName("script"));
for (WebElement scriptTag : scriptTags)
{
    if (scriptTag.getAttribute("innerHTML").contains("var rlSerial = '1058358';"))
    {
        // assertTrue()
        break;
    }
}

编辑: 我只是运行下面的代码,它对我来说很好......一定是你最终的东西。

driver.get("http://www.google.com");
String searchText = "document.body.style.visibility";
List<WebElement> scriptTags = driver.findElements(By.tagName("script"));
for (WebElement scriptTag : scriptTags)
{
    String text = scriptTag.getAttribute("outerHTML");
    if (text.contains(searchText))
    {
        System.out.println("Found it: " + text);
        // your assertTrue(...) goes here
        break;
    }
}

控制台:

Found it: <script>if(google.j.b)document.body.style.visibility='hidden';</script>