![](/img/trans.png)
[英]collapse all elements for loaded xml in webbrowser control using c#
[英]C# using WebBrowser control and need to access DOM elements
我在使用C#的WinForm應用程序中加載了一個網頁
我需要以編程方式在該頁面上的特定字段中鍵入數據(不使用WATIN)。
如果有人有其他解決方案,我願意接受。
有問題的頁面沒有AJAX或JavaScript。 它們是簡單的HTML數據輸入表單。
您可以使用WebBrowser
控件的Document
屬性來執行此操作:
C#代碼:
if (webBrowser1.Document == null) return;
var form = webBrowser1.Document.Forms[0]; //form element
var input = form.Children[0]; //input element
input.SetAttribute("value","input value"); //set the input value
form.InvokeMember("submit"); //submit the form
演示HTML頁面加載到WebBrowser
控件中:
<html>
<head>
<title></title>
</head>
<body>
<form method="post" action="">
<input type="text" name="testInput" value="test"/>
<input type="submit" value="submit"/>
</form>
</body>
</html>
假設您正在將網頁加載到WinForm應用程序上的WebBrowser控件中,則應該能夠通過WebBrowser.HtmlDocument.DomDocument屬性訪問文檔。 這是通過MSHTML.IHTMLDocument2接口對該頁面的IE DOM的非托管引用。
使用WebClient下載頁面,並使用HtmlAgilityPack對其進行解析。
一個例子:
using (var wc = new WebClient())
{
var page = wc.DownloadString(url);
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(page);
//XPath
var title = doc.DocumentNode.SelectSingleNode("//title").InnerText;
var text = doc.DocumentNode.SelectSingleNode("//div[@id='readInner']")
.InnerText;
//Linq
var text = doc.DocumentNode.Descendants("div")
.Where(n => n.Attributes["id"].Value == "readInner")
.First()
.InnerText;
}
使用MSHTML.Dll和SHDocVw.dll
我只是粘貼將代碼從winform轉換為IE瀏覽器的代碼,在該瀏覽器中,您只需單擊按鈕即可將數據傳輸到網頁,但該網頁以及您的HTML網頁上的控件都相同
private SHDocVw.InternetExplorer TargetIE = null;
string url;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
GetTheIEObjectFromSystem);
SendTextToActiveElementWithSubmitOptionSet();
}
private void GetTheIEObjectFromSystem(
{
SHDocVw.ShellWindows SWs = new SHDocVw.ShellWindows();
foreach (SHDocVw.InternetExplorer internetExplorer in SWs)
{
url = internetExplorer.LocationURL;
TargetIE = internetExplorer;
return;
}
}
private void SendTextToActiveElementWithSubmitOptionSet()
{
mshtml.IHTMLDocument2 document = null;
document = TargetIE.Document as mshtml.IHTMLDocument2;
if (!document.activeElement.isTextEdit)
{
MessageBox.Show("Active element is not a text-input system");
}
else
{
HTMLInputElement HTMLI;
HTMLI = document.activeElement as HTMLInputElement;
var tag = HTMLI.document as mshtml.HTMLDocumentClass;
mshtml.IHTMLElementCollection hTMLElementCollection = tag.getElementsByTagName("input");
//for (int i = 0; i < a.length; i++)
{
foreach (mshtml.HTMLInputElement el in hTMLElementCollection)
{
switch (el.id)
{
case "txtFirstName":
el.value = textBox1.Text;
break;
case "txtLastName":
el.value = textBox2.Text;
break;
case "txtAddress":
el.value = textBox3.Text;
break;
case "txtMobile":
el.value = textBox4.Text;
break;
}
}
}
}
}
您可以根據需要進行更改,我敢肯定
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.