HTML 민첩성 팩으로 속성 값을 선택합니다
-
23-08-2019 - |
문제
HTML 민첩성 팩 과이 XPath를 사용하여 HTML 문서에서 특정 이미지를 검색하려고합니다.
//div[@id='topslot']/a/img/@src
내가 볼 수있는 한, 그것은 SRC-Attribute를 찾지 만 IMG- 태그를 반환합니다. 왜 그런 겁니까?
내부 html/내부 텍스트 또는 설정이 설정 될 것으로 예상되지만 둘 다 빈 줄입니다. OUTERHTML은 완전한 IMG 태그로 설정됩니다.
HTML 민첩성 팩에 대한 문서가 있습니까?
해결책
HTML 민첩성 팩 지원하지 않습니다 속성 선택.
다른 팁
사용하는 경우 속성을 직접 잡을 수 있습니다. HtmlNavigator
대신에.
//Load document from some html string
HtmlDocument hdoc = new HtmlDocument();
hdoc.LoadHtml(htmlContent);
//Load navigator for current document
HtmlNodeNavigator navigator = (HtmlNodeNavigator)hdoc.CreateNavigator();
//Get value from given xpath
string xpath = "//div[@id='topslot']/a/img/@src";
string val = navigator.SelectSingleNode(xpath).Value;
"getAttributeValue"방법을 사용할 수 있습니다.
예시:
//[...] code before needs to load a html document
HtmlAgilityPack.HtmlDocument htmldoc = e.Document;
//get all nodes "a" matching the XPath expression
HtmlNodeCollection AllNodes = htmldoc.DocumentNode.SelectNodes("*[@class='item']/p/a");
//show a messagebox for each node found that shows the content of attribute "href"
foreach (var MensaNode in AllNodes)
{
string url = MensaNode.GetAttributeValue("href", "not found");
MessageBox.Show(url);
}
HTML 민첩성 팩은 곧 지원할 것입니다.
http://htmlagilitypack.codeplex.com/thread/view.aspx?threadid=204342
HTML 민첩성 팩을 사용한 속성을 읽고 쓰는 것
htmlagilitypack에서 속성을 읽고 설정할 수 있습니다. 이 예제는 <html> 태그를 선택하고 'Lang'(언어) 속성이 존재하는 경우 'Lang'속성을 읽고 씁니다.
아래의 예에서 Doc.LoadHtml (this.all), "this.all"은 HTML 문서의 문자열 표현입니다.
읽고 쓰기:
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(this.All);
string language = string.Empty;
var nodes = doc.DocumentNode.SelectNodes("//html");
for (int i = 0; i < nodes.Count; i++)
{
if (nodes[i] != null && nodes[i].Attributes.Count > 0 && nodes[i].Attributes.Contains("lang"))
{
language = nodes[i].Attributes["lang"].Value; //Get attribute
nodes[i].Attributes["lang"].Value = "en-US"; //Set attribute
}
}
읽기 전용 :
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(this.All);
string language = string.Empty;
var nodes = doc.DocumentNode.SelectNodes("//html");
foreach (HtmlNode a in nodes)
{
if (a != null && a.Attributes.Count > 0 && a.Attributes.Contains("lang"))
{
language = a.Attributes["lang"].Value;
}
}
이미지의 속성을 얻기 위해 다음 방법을 사용했습니다.
var MainImageString = MainImageNode.Attributes.Where(i=> i.Name=="src").FirstOrDefault();
속성 이름을 지정하여 값을 얻을 수 있습니다. 속성 이름을 모르는 경우 노드를 가져온 후에 중단 점을 제공하고 그 위에 호버링하여 속성을보십시오.
내가 도와주기를 바랍니다.