如何登录网页并在C#中检索其内容?

有帮助吗?

解决方案 4

string postData = "userid=ducon";
            postData += "&username=camarche" ;
            byte[] data = Encoding.ASCII.GetBytes(postData);
            WebRequest req = WebRequest.Create(
                URL);
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            req.ContentLength = data.Length;
            Stream newStream = req.GetRequestStream();
            newStream.Write(data, 0, data.Length);
            newStream.Close();
            StreamReader reader = new StreamReader(req.GetResponse().GetResponseStream(), System.Text.Encoding.GetEncoding("iso-8859-1"));
            string coco = reader.ReadToEnd();

其他提示

这取决于登录所需的内容。您可以使用webclient将登录凭据发送到服务器的登录页面(通过任何方法,GET或POST),但这不会持久存在cookie。有一个方式来让webclient处理cookie,所以您可以将登录信息发布到服务器,然后使用相同的webclient请求您想要的页面,然后对页面执行任何操作。

查看 System.Net.WebClient ,或了解更多高级要求 System.Net.HttpWebRequest / System.Net.HttpWebResponse

至于实际应用这些:你必须研究你想要抓取的每个页面的html源代码,以便准确了解Http要求它的期望。

你是什么意思“登录”?

如果子文件夹在操作系统级别受到保护,并且当您去那里时浏览器会弹出登录对话框,则需要在HttpWebRequest上设置Credentials属性。

如果网站拥有自己的基于cookie的会员/登录系统,则必须使用HttpWebRequest首先响应登录表单。

使用 WebClient 上课。

Dim Html As String

Using Client As New System.Net.WebClient()
    Html = Client.DownloadString("http://www.google.com")
End Using

您可以在WebClient对象中使用构建,而不是自己创建请求。

WebClient wc = new WebClient();
wc.Credentials = new NetworkCredential("username", "password");
string url = "http://foo.com";          
try
{
    using (Stream stream = wc.OpenRead(new Uri(url)))
    {
        using (StreamReader reader = new StreamReader(stream))
        {
            return reader.ReadToEnd();
             }
    }
}
catch (WebException e)
{
    //Error handeling
}

试试这个:

public string GetContent(string url)  
{ 
  using (System.Net.WebClient client =new System.Net.WebClient()) 
  { 
  return client.DownloadString(url); 
  } 
} 
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top