C# 打开浏览器,自动完成表单组件并提交
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15447864/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Open webbrowser, auto complete form components and submit
提问by Simon
We are currently investigating a method of creating a WPF/winforms application that we can set up internally to :-
我们目前正在研究一种创建 WPF/winforms 应用程序的方法,我们可以在内部对其进行设置:-
- automatically open a new instance of a web browser to a predefined URL
- automatically complete required fields with predefined data
- automatically submit form and wait for the next page to load
- automatically complete required fields with predefined data (page 2)
- automatically submit form and wait for the next page to load (etc)
- 自动将 Web 浏览器的新实例打开到预定义的 URL
- 使用预定义数据自动完成必填字段
- 自动提交表单并等待下一页加载
- 使用预定义数据自动填写必填字段(第 2 页)
- 自动提交表单并等待下一页加载(等)
after much investigation, the only thing we have managed to find is the opening up of a web browser via :-
经过大量调查,我们唯一找到的是通过以下方式打开网络浏览器:-
object o = null;
SHDocVw.InternetExplorer ie = new SHDocVw.InternetExplorer();
IWebBrowserApp wb = (IWebBrowserApp)ie;
wb.Visible = true;
wb.Navigate(url, ref o, ref o, ref o, ref o);
Any advice / reading recommendations would be appreciated on how to complete the process.
关于如何完成该过程的任何建议/阅读建议将不胜感激。
采纳答案by KF2
I wrote an example for filling in an element in a html page. You must do something like this:
我写了一个例子来填充 html 页面中的元素。你必须做这样的事情:
Winform
登录
public Form1()
{
InitializeComponent();
//navigate to you destination
webBrowser1.Navigate("https://www.certiport.com/portal/SSL/Login.aspx");
}
bool is_sec_page = false;
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (!is_sec_page)
{
//get page element with id
webBrowser1.Document.GetElementById("c_Username").InnerText = "username";
webBrowser1.Document.GetElementById("c_Password").InnerText = "pass";
//login in to account(fire a login button promagatelly)
webBrowser1.Document.GetElementById("c_LoginBtn_c_CommandBtn").InvokeMember("click");
is_sec_page = true;
}
//secound page(if correctly aotanticate
else
{
//intract with sec page elements with theire ids and so on
}
}
Wpf
湿巾
public MainWindow()
{
InitializeComponent();
webBrowser1.Navigate(new Uri("https://www.certiport.com/portal/SSL/Login.aspx"));
}
bool is_sec_page = false;
mshtml.HTMLDocument htmldoc;
private void webBrowser1_LoadCompleted(object sender, NavigationEventArgs e)
{
htmldoc = webBrowser1.Document as mshtml.HTMLDocument;
if (!is_sec_page)
{
//get page element with id
htmldoc.getElementById("c_Username").innerText = "username";
//or
//htmldoc.getElementById("c_Username")..SetAttribute("value", "username");
htmldoc.getElementById("c_Password").innerText = "pass";
//login in to account(fire a login button promagatelly)
htmldoc.getElementById("c_LoginBtn_c_CommandBtn").InvokeMember("click");
is_sec_page = true;
}
//secound page(if correctly aotanticate
else
{
//intract with sec page elements with theire ids and so on
}
}
Just navigate to specific URL and fill page element.
只需导航到特定的 URL 并填充页面元素。
回答by Alexander Manekovskiy
If I understood you right you want to open some URL in web browser and then interact with site as a normal user would. For such task I can suggest taking look at Selenium. While it is typically used as a regression testing automation tool no one can stop you from using it as a browser automation tool.
如果我理解你是对的,你想在网络浏览器中打开一些 URL,然后像普通用户一样与站点交互。对于这样的任务,我可以建议看看Selenium。虽然它通常用作回归测试自动化工具,但没有人可以阻止您将其用作浏览器自动化工具。
Selenium has detailed documentationand big community. Most probably you will want to use Selenium WebDriverwhich is available via nuget.
Selenium 有详细的文档和庞大的社区。很可能你会想要使用Selenium WebDriver,它可以通过nuget 获得。
Below is a little example of typical Selenium "script" (taken as-is from documentation):
下面是典型的 Selenium “脚本”的一个小例子(从文档中按原样获取):
// Create a new instance of the Firefox driver.
// Notice that the remainder of the code relies on the interface,
// not the implementation.
// Further note that other drivers (InternetExplorerDriver,
// ChromeDriver, etc.) will require further configuration
// before this example will work. See the wiki pages for the
// individual drivers at http://code.google.com/p/selenium/wiki
// for further information.
IWebDriver driver = new FirefoxDriver();
//Notice navigation is slightly different than the Java version
//This is because 'get' is a keyword in C#
driver.Navigate().GoToUrl("http://www.google.com/");
// Find the text input element by its name
IWebElement query = driver.FindElement(By.Name("q"));
// Enter something to search for
query.SendKeys("Cheese");
// Now submit the form. WebDriver will find the form for us from the element
query.Submit();
// Google's search is rendered dynamically with JavaScript.
// Wait for the page to load, timeout after 10 seconds
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
wait.Until((d) => { return d.Title.ToLower().StartsWith("cheese"); });
// Should see: "Cheese - Google Search"
System.Console.WriteLine("Page title is: " + driver.Title);
//Close the browser
driver.Quit();
Personally I can suggest to think and organize scripts in terms of user actions (register, login, fill form, select something in grid, filter grid, etc.). This will give a good shape and readability to scripts instead of messy hardcoded code chunks. The script in this case can look similar to this:
我个人建议根据用户操作(注册、登录、填写表单、在网格中选择某些内容、过滤器网格等)来思考和组织脚本。这将为脚本提供良好的形状和可读性,而不是凌乱的硬编码代码块。这种情况下的脚本可能类似于:
// Fill username and password
// Click on button "login"
// Wait until page got loaded
LoginAs("[email protected]", "johndoepasswd");
// Follow link in navigation menu
GotoPage(Pages.Reports);
// Fill inputs to reflect year-to-date filter
// Click on filter button
// Wait until page refreshes
ReportsView.FilterBy(ReportsView.Filters.YTD(2012));
// Output value of Total row from grid
Console.WriteLine(ReportsView.Grid.Total);
回答by Limitless isa
if (webBrowser1.Document != null)
{
HtmlElementCollection elems = webBrowser1.Document.GetElementsByTagName("input");
foreach (HtmlElement elem in elems)
{
String nameStr = elem.GetAttribute("name");
if (nameStr == "email")
{
webBrowser1.Document.GetElementById(nameStr).SetAttribute("value", "[email protected]");
}
}
}