Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
208 views
in Technique[技术] by (71.8m points)

java - put a string with html/Javascript into selenium webdriver

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.

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

Here comes an example:

<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>

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you don't want to create a file or load a URL before being able to replace the content of the page, you can always leverage the Data URLs feature, which supports HTML, CSS and JavaScript:

ChromeDriver driver = new ChromeDriver();
html_content = """
<html>
     <head></head>
     <body>
         <div>
             Hello World =)
         </div>
     </body>
</html>
"""

driver.get("data:text/html;charset=utf-8," + html_content)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...