c# 怎么截取网页代码中的指定字符串

2024-11-30 10:39:35
推荐回答(3个)
回答1:

C#获取指定网页HTML原代码可使用 WebClient WebRequest HttpWebRequest 三种方式来实现。
当然也可使用webBrowse!在此就不研究webBrowse如何获取了。
WebClient

private string GetWebClient(string url)
{
string strHTML = "";
WebClient myWebClient = new WebClient();
Stream myStream = myWebClient.OpenRead(url);
StreamReader sr = new StreamReader(myStream, System.Text.Encoding.GetEncoding("utf-8"));
strHTML = sr.ReadToEnd();
myStream.Close();
return strHTML;
}

WebRequest

private string GetWebRequest(string url)
{
Uri uri = new Uri(url);
WebRequest myReq = WebRequest.Create(uri);
WebResponse result = myReq.GetResponse();
Stream receviceStream = result.GetResponseStream();
StreamReader readerOfStream = new StreamReader(receviceStream, System.Text.Encoding.GetEncoding("utf-8"));
string strHTML = readerOfStream.ReadToEnd();
readerOfStream.Close();
receviceStream.Close();
result.Close();
return strHTML;
}

HttpWebRequest

private string GetHttpWebRequest(string url)
{
Uri uri = new Uri(url);
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(uri);
myReq.UserAgent = "User-Agent:Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705";
myReq.Accept = "*/*";
myReq.KeepAlive = true;
myReq.Headers.Add("Accept-Language", "zh-cn,en-us;q=0.5");
HttpWebResponse result = (HttpWebResponse)myReq.GetResponse();
Stream receviceStream = result.GetResponseStream();
StreamReader readerOfStream = new StreamReader(receviceStream, System.Text.Encoding.GetEncoding("utf-8"));
string strHTML = readerOfStream.ReadToEnd();
readerOfStream.Close();
receviceStream.Close();
result.Close();
return strHTML;
}

注意“utf-8”应与指定网页的编码对应。
总结
可以看到HttpWebRequest 方式最复杂,但确提供了更多的选择性。

回答2:

你是用什么得到的网页源代码?
httpwebrequest还是Webbrowser?
第一种情况就很简单:
string s="你的内容";
int i=s.IndexOf("OLDSRC=\"");
int j=s.LastIndexOf("\"");
s=s.Substring(i,j-i);

第二种情况:
可以用循环来截取,然后来判断

回答3:

用正规表达式很好搞定的

string text = "DSRC=\"23333.jpg\"";
string pat = "\"(.+?)\"";

Regex r = new Regex(pat, RegexOptions.IgnoreCase);

Match m = r.Match(text);

while (m.Success)
{
........

}