c# 获取html中指定标签信息,c# – 如何解析图像标签的HTML字符串以获取SRC信息?...
如果你的輸入字符串是有效的XHTML,你可以把它當作xml,將其加載到一個xmldocument中,然后執行XPath魔術:)但并不總是如此。
否則你可以嘗試這個功能,這將返回從HtmlSource的所有圖像鏈接:
public List FetchLinksFromSource(string htmlSource)
{
List links = new List();
string regexImgSrc = @"]*?src\s*=\s*[""']?([^'"" >]+?)[ '""][^>]*?>";
MatchCollection matchesImgSrc = Regex.Matches(htmlSource, regexImgSrc, RegexOptions.IgnoreCase | RegexOptions.Singleline);
foreach (Match m in matchesImgSrc)
{
string href = m.Groups[1].Value;
links.Add(new Uri(href));
}
return links;
}
你可以這樣使用它:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.example.com");
request.Credentials = System.Net.CredentialCache.DefaultCredentials;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
using(StreamReader sr = new StreamReader(response.GetResponseStream()))
{
List links = FetchLinksFromSource(sr.ReadToEnd());
}
}
總結
以上是生活随笔為你收集整理的c# 获取html中指定标签信息,c# – 如何解析图像标签的HTML字符串以获取SRC信息?...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 搞怪的html代码,这个恶搞网页代码是肿
- 下一篇: php __FILE__,__CLASS