使用C#从Chrome中现有的打开选项卡中检索值

Retrieve values from existing open tab in Chrome using C#

本文关键字:选项 检索 Chrome 使用      更新时间:2023-09-26

我正在尝试使用c#.net构建一个控制台应用程序。我需要一个特定的功能,即从外部网站检索值。问题是我们需要登录该网站。我可以使用process.start打开我需要的页面。使用我需要的值登录chrome。。但问题是从第页检索值时。。我想过获得源代码,但每次尝试都不需要会话,因此我只获得错误页面源代码,因为我只是输入URL n而没有访问已经打开的选项卡?有没有其他方法可以使用JavaScript或c#?

使用WebClient API登录并下载页面数据。为了维护会话,您需要使其具有cookie意识。您需要添加对System.Web程序集的引用,才能在控制台应用程序中使用此API。

public class CookieAwareWebClient : WebClient
{
    public CookieAwareWebClient()
    {
        CookieContainer = new CookieContainer();
    }
    public CookieContainer CookieContainer { get; private set; }
    protected override WebRequest GetWebRequest(Uri address)
    {
        var request = (HttpWebRequest)base.GetWebRequest(address);
        request.CookieContainer = CookieContainer;
        return request;
    }
}

现在像一样使用它

using (var client = new CookieAwareWebClient())
{
    var values = new NameValueCollection
    {
        { "username", "john" },
        { "password", "secret" },
    };
    client.UploadValues("http://domain.loc/logon.aspx", values);
    // If the previous call succeeded we now have a valid authentication cookie
    // so we could download the protected page
    string result = client.DownloadString("http://domain.loc/testpage.aspx");
}

我从WebClient借用了这段代码,使用凭据

访问页面