C#获取网页内容并返回内容
时间: 2024-06-08 19:07:26 浏览: 165
C#获取网页内容
可以使用C#中的HttpWebRequest和HttpWebResponse类来获取网页内容,以下是示例代码:
```csharp
using System;
using System.IO;
using System.Net;
using System.Text;
public static string GetWebPageContent(string url)
{
string content = "";
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36";
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader streamReader = new StreamReader(stream, Encoding.UTF8);
content = streamReader.ReadToEnd();
streamReader.Close();
stream.Close();
response.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return content;
}
```
调用方法:
```csharp
string url = "https://www.example.com";
string content = GetWebPageContent(url);
Console.WriteLine(content);
```
阅读全文