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

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

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

查看System.Net.WebClient ,或者更高级的要求System.Net.HttpWebRequest/System.Net.HttpWebResponse

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

你是怎么说“登录”的?

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

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

 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类。

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