简体   繁体   中英

How to get element details from script tag using JavaScript in selenium webdriver?

My problem lies on this page

There is a canvas element on this page which is an image having a number which changes whenever you refresh page or do anything on the page which requires reloading.

In the source code what I see is only this:

<div class="row">
      <div class="large-10 columns">
        <canvas id="canvas" width="599" height="200" style="border:1px dotted;"></canvas>
      </div>
    </div>

So in-short there is nothing I can do with this info on the outer html but when I went to network section and saw the response code in which I found this code which uses javascript:

    <script>var canvas_el = document.getElementById('canvas');
var canvas = canvas_el.getContext('2d');
canvas.font = '60px Arial';
canvas.strokeText('Answer: 19403',90,112);
</script>

Now my problem is how can I write javascript(I don't know that much of javascript) in selenium webdriver to get this details(Specifically strokeText) under the script tag which are otherwise not there on the source code. I am looking for some solution using JavascriptExecutor .

You had the right idea with using JavascriptExecutor . I found the basic strategy here .

final By SCRIPT = By.tagName("script");

List<WebElement> scripts = new WebDriverWait(driver, 5)
        .until(ExpectedConditions.presenceOfAllElementsLocatedBy(SCRIPT));

JavascriptExecutor js = (JavascriptExecutor) driver;
String query = "return document.getElementsByTagName(\"script\")[arguments[0]].innerHTML;";     
Pattern p = Pattern.compile("canvas.strokeText\\('Answer: \\d+'");
Pattern p2 = Pattern.compile("\\d+");

String number = IntStream.range(0, scripts.size())
        .mapToObj(i -> (String)js.executeScript(query, i))
        .map(string -> p.matcher(string))
        .filter(m -> m.find())
        .map(m -> p2.matcher(m.group()))
        .filter(m -> m.find())
        .map(m -> m.group())
        .findFirst()
        .orElse(null);
System.out.println(number);  // prints the number rendered on the page

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM