如果我理解正确,您想在网络浏览器中打开一些 URL,然后像普通用户一样与网站交互。对于这样的任务,我可以建议看看Selenium。虽然它通常用作回归测试自动化工具,但没有人可以阻止您将其用作浏览器自动化工具。
Selenium 有详细的文档和庞大的社区。很可能您会想要使用可通过nuget获得的Selenium WebDriver。
下面是一个典型的 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();
就我个人而言,我可以建议根据用户操作(注册、登录、填写表单、在网格中选择内容、过滤网格等)来思考和组织脚本。这将为脚本提供良好的形状和可读性,而不是杂乱的硬编码代码块。这种情况下的脚本可能类似于:
// Fill username and password
// Click on button "login"
// Wait until page got loaded
LoginAs("johndoe@domain.com", "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);