web-dev-qa-db-ja.com

ウェブブラウザを開き、フォームコンポーネントをオートコンプリートして送信します

現在、内部でセットアップできるWPF/winformsアプリケーションを作成する方法を調査しています:-

  1. 事前定義されたURLでWebブラウザの新しいインスタンスを自動的に開きます
  2. 事前定義されたデータで必須フィールドに自動的に入力します
  3. フォームを自動的に送信し、次のページが読み込まれるのを待ちます
  4. 事前定義されたデータを使用して必須フィールドに自動的に入力します(2ページ)
  5. フォームを自動的に送信し、次のページが読み込まれるのを待ちます(など)

多くの調査の結果、私たちが見つけた唯一のことは、次の方法でWebブラウザを開くことです:-

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);

プロセスを完了する方法についてのアドバイス/読書の推奨事項をいただければ幸いです。

7
Simon

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
                }
            }

特定のURLに移動して、ページ要素に入力するだけです。

18
KF2

私があなたの言うことを正しく理解していれば、WebブラウザでURLを開いてから、通常のユーザーと同じようにサイトを操作したいと思うでしょう。そのようなタスクについては、 Selenium を見てみることをお勧めします。これは通常、回帰テストの自動化ツールとして使用されますが、ブラウザーの自動化ツールとしての使用を阻止することはできません。

Seleniumには詳細な ドキュメント と大きな コミュニティ があります。おそらく、 Selenium WebDriver を使用することをお勧めします。これは nuget から入手できます。

以下は、典型的な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("[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);
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]");
    }
  }
}
2
Limitless isa