0

The Excel VBA code below opens a Selenium browser and navigates to the url in Sheet4!B2 (http://google.com).

Instead of the url, I'm replacing Sheet4!B2 with html code.

How do I inject html code into Selenium instead of navigating to the url?

All of the sources I happened to stumble upon point to running a local html file with code webdriver.get("file:///D:/folder/abcd.html");. This is very inconvenient since one can simply run the html code within Excel. Does Selenium allow you to do this?

Public Sub NavigateToURL1()
    driver.Get [Sheet4!B2]
End Sub
1
  • Selenium is for browser automation. If you are going to avoid a browser why not just work direct with HTML document? Commented May 5, 2018 at 10:28

1 Answer 1

1

You can achieve your stated aim with the following, which opens an empty browser window and render the HTML there.

Code:

Option Explicit
Public Sub GetHTMLfromCell()
  Dim html  As String
  html = ThisWorkbook.Worksheets("Sheet4").Range("B2").Value2
  Const WRITETOPAGE As String = _
    "var txt=arguments[0];" & _
    "setTimeout(function(){" & _
    " document.open();" & _
    " document.write(txt);" & _
    " document.close();" & _
    "}, 0);"

  Dim d As New ChromeDriver
  With d
      .Get "about:blank"
      .ExecuteScript WRITETOPAGE, html
      Debug.Print .FindElementByTag("p").Text
      .Quit
  End With
End Sub

Credit to @FlorentB for this method.

Sample HTML in B2

<!DOCTYPE html>
<html>
<body>

<h1>My First Heading</h1>

<p>My first paragraph.</p>

</body>
</html>

Output:

Output

References:

  1. put a string with html/Javascript into selenium webdriver
  2. Modify innerHTML using selenium
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.