我在使用C#
的WinForm应用程序中加载了一个网页我需要以编程方式将数据输入到该页面上的特定字段(不使用WATIN)。
如果有人有任何其他解决方案,我愿意接受。
相关网页没有AJAX或JavaScript。它们是简单的HTML数据输入表单。
答案 0 :(得分:4)
您可以使用Document
控件的WebBrowser
属性执行此操作:
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
演示加载到WebBrowser
控件中的HTML页面:
<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>
答案 1 :(得分:3)
假设您正在将网页加载到WinForm应用程序的WebBrowser控件中,您应该能够通过WebBrowser.HtmlDocument.DomDocument属性访问该文档。这是通过MSHTML.IHTMLDocument2接口对页面的IE DOM进行的非托管引用。
答案 2 :(得分:3)
使用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;
}
答案 3 :(得分:1)
使用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;
}
}
}
}
}
您可以根据需要进行更改我相信它可以正常工作