[英]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. 此页面上有一个canvas元素,它是一张图像,其编号会在您刷新页面或在页面上执行任何需要重新加载的操作时更改。
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: 因此,简而言之,我无法使用外部html上的此信息,但是当我进入网络部分并看到响应代码时,在其中找到了使用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. 现在我的问题是我该如何在Selenium Webdriver中编写javascript(我不太了解javascript),以在script标签下获得此详细信息(特别是strokeText),否则该标签将不在源代码上显示。 I am looking for some solution using JavascriptExecutor . 我正在寻找使用JavascriptExecutor的解决方案。
You had the right idea with using JavascriptExecutor
. 使用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.