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
Community
  • 1
  • 1
ninjachuku
  • 39
  • 1
  • 7
  • Selenium is for browser automation. If you are going to avoid a browser why not just work direct with HTML document? – QHarr May 05 '18 at 10:28

1 Answers1

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
QHarr
  • 83,427
  • 12
  • 54
  • 101