在从C#string生成的HTML上运行javascript
发布时间:2020-12-15 22:47:18 所属栏目:百科 来源:网络整理
导读:我想在从C#string生成的 HTML上运行 javascript. (无需打开浏览器 – 只需C#代码) 就像是: string myHTML = 'div id="divTest"This is testbr/br//div'; Javascript应该是: function test { return document.getElementById('divTest').offsetHeight;} 我
我想在从C#string生成的
HTML上运行
javascript.
(无需打开浏览器 – 只需C#代码) 就像是: string myHTML = '<div id="divTest">This is test<br/><br/></div>'; Javascript应该是: function test { return document.getElementById('divTest').offsetHeight; } 我已经尝试过检查一些无头浏览器,比如PhantomJS和Optimus–但它们没有渲染字符串的选项(只能通过http://google.com/这样的网址打开网页.有没有办法通过C#实现这一目标? 解决方法
以下是为我工作:
string html = "<html><head></head><body><div id="divTest">This is test<br/><br/></div></body></html>"; string script1 = "return document.getElementById('divTest').innerText"; string script2 = "return document.getElementById('divTest').offsetHeight"; var options = new PhantomJSOptions(); options.AddAdditionalCapability("javascriptEnabled",true); var driver = new PhantomJSDriver(options); driver.Url = "file://dummy.html"; driver.Navigate(); driver.ExecutePhantomJS("document.write('" + html + "');"); var test1 = driver.ExecutePhantomJS(script1); //Returns: This is a test var test2 = driver.ExecutePhantomJS(script2); //Returns: 40 您需要安装Selenium.WebDriver NuGet并从http://phantomjs.org/download.html下载PhantomJS exe,它需要与您的exe或PATH位于同一文件夹中. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |