如何登录或登录我的程序内的网站?

时间:2013-09-20 10:03:14

标签: c# .net winforms

我想让我的Winforms程序有一个按钮,按下时会执行以下操作:

  1. 打开浏览器
  2. 导航到网站
  3. 从文件或文本框中读取用户名和密码
  4. 登录该网站,甚至从我的程序中获取信息并登录。
  5. 例如,我想通过Facebook或论坛等网站进行此操作。 这是可能的,我该怎么做?

1 个答案:

答案 0 :(得分:3)

是;这在技术上是可行的。

对于制作WinForms应用程序,我不认为这个网站是合适的,因为它是关于特定的,更窄的问题。

要打开Web浏览器,导航到页面并登录,请查看浏览器自动化库。我推荐Selenium Webdriver,因为它适用于多个浏览器,似乎是最成熟的浏览器。您可以使用NuGet将其添加到项目中。

以下是使用Facebook执行此操作的一些示例代码:

using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using System;

class Program
{
    static void Main(string[] args)
    {
        var facebookDetails = new WebPageAuthenticationDetails
        {
            HomePageAddress = new Uri("https://www.facebook.com/"),
            UsernameLocator = By.Id("email"),
            PasswordLocator = By.Id("pass"),
            SubmitLocator = By.XPath("//input[@value='Log in']"),
        };

        //Don't dispose this or the browser will be closed after logging in.
        var browserDriver = new FirefoxDriver(); //Or use a different browser if you want (Firefox is easiest to use, though)
        var pageAccessor = new WebPageAccessor(browserDriver, facebookDetails);
        pageAccessor.LogIn("example_username", "example_password");
    }
}

class WebPageAccessor
{
    private readonly IWebDriver driver;
    private readonly WebPageAuthenticationDetails pageDetails;

    public WebPageAccessor(IWebDriver driver, WebPageAuthenticationDetails details)
    {
        this.driver = driver;
        this.pageDetails = details;
    }

    public void LogIn(string username, string password)
    {
        driver.Navigate().GoToUrl(pageDetails.HomePageAddress);

        if (pageDetails.LogInLinkLocator != null)
            Click(pageDetails.LogInLinkLocator);

        Type(pageDetails.UsernameLocator, username);
        Type(pageDetails.PasswordLocator, password);
        Click(pageDetails.SubmitLocator);
    }

    private void Click(By locator)
    {
        driver.FindElement(locator).Click();
    }

    private void Type(By fieldLocator, string text)
    {
        driver.FindElement(fieldLocator).SendKeys(text);
    }
}

class WebPageAuthenticationDetails
{
    public Uri HomePageAddress { get; set; }

    /// <summary>
    /// Only needed if a log-in link first needs to be clicked.
    /// </summary>
    public By LogInLinkLocator { get; set; }
    public By UsernameLocator { get; set; }
    public By PasswordLocator { get; set; }
    public By SubmitLocator { get; set; } //Because some sites don't use HTML submit buttons to submit
}

选择浏览器自动化库可能很困难。如果您不知道使用哪一个,只需进行一些Google搜索;之前已经讨论过了。