[英]Evaluate Html/javascript from c#
我的任務是為一個非常新穎的問題找到解決方案。 我必須進行各種各樣的httpclient調用才能針對第三方供應商進行身份驗證。 但是,此過程的一部分涉及在javascript中創建動態生成的值並將其傳遞給表單,然后將該表單發布到第三方。 當我使用httpclient類時,顯然無法生成/運行javascript,因此該過程在此處停止(這些值的發布會為中間步驟創建一個重要的身份驗證cookie)。
因此,我希望能夠使用包含表單和一些javascript的簡單html,並讓我的c#代碼對此進行評估,然后檢索javscript分配給表單的值。 然后,我將使用這些值並繼續進行工作流程。
我可以走一條笨拙的路線,並使用webbrowser控件。 但是,由於這是在非可視環境中使用的,所以我希望能夠將html字符串傳遞到某種模擬器中,並以解析的形式接收返回的html作為返回。 以下是我要處理的簡單html的示例:
<html>
<head>
<script type="text/javascript">
function testLoad() {
document.forms[0].elements[0].value = "some guid id plus the date:" + Date.getDate + 'some random js value';
document.forms[0].elements[1].value = decodeURIComponent(document.forms[0].elements[1].value);
document.forms[0].elements[2].value = decodeURIComponent(document.forms[0].elements[2].value);
// optionally submit -or just get the returned form values and post from htmlclient
document.forms[0].submit();
}</script>
<noscript>Please enable JavaScript to view the page content.</noscript>
</head>
<body onload="testLoad()">
<form method="POST" action="/" />
<input type="hidden" name="test_id" value="idstuff" />
<input type="hidden" name="test_123" value="encoded value" />
<input type="hidden" name="test_another" value="1.01" />
</form>
</body>
</html>
從仿真過程返回html后,我將使用HtmlAgilityPack捕獲由javascript函數(testLoad())填充的表單值,並繼續進行下一步。
我的目標是太高了嗎,還是這座橋已經過了幾次? 我看過http ://wiki.awesomium.com,csExWB,jint和其他幾個文件,但似乎沒有一個采用我希望在這里使用的非常簡單的方法。 認為我的任務是能夠使用初始html作為參數,並使emlulator返回修補的 html。
希望上面的內容很清楚-我希望從服務器端進程中評估html / js,然后進入我的c#工作流程中的下一個進程!
[edit]-這看起來非常有希望: http : //www.tomdupont.net/2013/08/phantomjs-headless-browser-for-net-webdriver.html 。 我在這里已經掌握了技巧,並且正在將PhantomJs與Selenium結合使用……到目前為止,太好了!!
[哦,只是要指出,這不是用於任何險惡的事情,有關的第三方還沒有適當的b2b api來允許我們之間進行互操作]
有PhantomJS ,可以通過JavaScript編寫腳本,並可以從C#作為外部進程運行 :
聽起來您需要一個無頭瀏覽器才能執行html / javascript。 在這里看看。
我更喜歡AngleSharp而不是HtmlAgilityPack。
AngleSharp還包含一個簡短的演示(項目),可將Jint (一個完全用.NET編寫的JavaScript解釋器)連接到該演示。 兩者都是PCL項目,它們可以毫無問題地協同工作。 那應該提供JavaScript / DOM中通常使用的所有內容。
一個非常簡單的示例如下所示:
static void SimpleScriptingSample()
{
//We require a custom configuration
var config = new Configuration();
//Including a script engine
config.Register(new JavaScriptEngine());
//And enabling scripting
config.IsScripting = true;
//This is our sample source, we will set the title and write on the document
var source = @"<!doctype html>
<html>
<head><title>Sample</title></head>
<body>
<script>
document.title = 'Simple manipulation...';
document.write('<span class=greeting>Hello World!</span>');
</script>
</body>";
var document = DocumentBuilder.Html(source, config);
//Modified HTML will be output
Console.WriteLine(document.DocumentElement.OuterHtml);
}
這將打印(序列化的)DOM,該DOM已經包含修改(例如新標題和插入的span元素)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.