把一个带有html / Javascript的字符串放到selenium webdriver中 [英] put a string with html/Javascript into selenium webdriver

查看:217
本文介绍了把一个带有html / Javascript的字符串放到selenium webdriver中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在内存中有一个html文档作为字符串。它包含一个< script> 标记,其中包含一个操作dom的小脚本。我现在想将该html页面加载到selenium webdriver中,并在脚本操作后返回页面。因为我已经在内存中使用了html,所以我不喜欢将html写入文件并将其作为文件加载到 driver.get(file:// path / to / file )。所以问题是,如果有可能达到我想要的目的。

I have a html document in memory as a string. It contains a <script> tag with a little script that manipulates the dom. I now want to load that html page into selenium webdriver and get back the page after the script manipulates it. Since I have the html already in memory, I don't like the idea much of writing the html into a file and load it as file with driver.get("file://path/to/file"). So the question is, if there is a possibility to achieve what I want.

如果webdriver无法做到,可能还有其他可能吗?

IF webdriver can't do it, maybe there is a possibility other than that?

以下是一个例子:

<html><head>
<script type="text/javascript">
function fill(){
    var i = "secret"
    document.forms[0].elements[1].value=i
}
</script>
</head><body onload="fill()">
<form method="POST"><input type="hidden" name="he1" value="">
<input type="hidden" name="he2" value="">
</form></body></html>

显然,我希望webdriver执行dom操作并根据脚本更改表单。

Obviously, I want the webdriver to perform the dom manipulation and change the form according to the script.

注意这只是一个例子。我需要运行的实际脚本做了更复杂的事情。

Note this is just an example. The actual script I need to run does much more complicated things.

推荐答案

你可以加载一个空页面,例如:

You could load an empty page eg:

<html></html>

然后设置它的innerHTML

And then set it's innerHTML

ChromeDriver driver = new ChromeDriver();
driver.get("file://empty-page.html");
String innerHtml = "<head>...</head><body onload="...">...</body>";
driver.executeScript("document.innerHTML = " + innerHtml);

然后触发身体上的加载事件

Then fire the load event on the body

driver.executeScript("$(document.body).trigger('load');");

然后得到结果HTML

Then get the resultant HTML

String result = driver.executeScript("document.body.innerHTML;");

这篇关于把一个带有html / Javascript的字符串放到selenium webdriver中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆