자주 정규식을 사용하여 html 텍스트 데이터에서 파일 이름을 추출하지만 html 민첩성 팩은 html 데이터를 구문 분석하는 데 유용하다고 들었습니다. html 데이터에서 모든 URL을 추출하기 위해 html 민첩성 팩을 어떻게 사용할 수 있습니까? 어느 누구도 샘플 코드를 안내해 줄 수 있습니까? 감사.
이것은 잘 작동하는 내 코드 샘플입니다.
using System.Text.RegularExpressions;
private ArrayList GetFilesName(string Source)
{
ArrayList arrayList = new ArrayList();
Regex regex = new Regex("(?<=src=\")([^\"]+)(?=\")", 1);
MatchCollection matchCollection = regex.Matches(Source);
foreach (Match match in matchCollection)
{
if (!match.get_Value().StartsWith("http://"))
{
arrayList.Add(Path.GetFileName(match.get_Value()));
}
match.NextMatch();
}
ArrayList arrayList1 = arrayList;
return arrayList1;
}
private string ReplaceSrc(string Source)
{
Regex regex = new Regex("(?<=src=\")([^\"]+)(?=\")", 1);
MatchCollection matchCollection = regex.Matches(Source);
foreach (Match match in matchCollection)
{
string value = match.get_Value();
string str = string.Concat("images/", Path.GetFileName(value));
Source = Source.Replace(value, str);
match.NextMatch();
}
string source = Source;
return source;
}
src
속성이 비어있는 모든 img
태그를 선택하십시오 (그렇지 않으면 속성 값을 가져 오는 동안 NullReferenceException이 발생합니다).
HtmlDocument html = new HtmlDocument();
html.Load(path_to_file);
var urls = html.DocumentNode.SelectNodes("//img[@src!='']")
.Select(i => i.Attributes["src"].Value);
같은 것 :
var doc = new HtmlDocument();
doc.LoadHtml(html);
var images = doc.DocumentNode.Descendants("img")
.Where(i => i.GetAttributeValue("src", null) != null)
.Select(i => i.Attributes["src"].Value);
src
속성이 설정된 문서의 모든 <img>
요소를 선택하고 이러한 URL을 반환합니다.