HTML Agility Pack 사용 방법
HTML Agility Pack 은 어떻게 사용 합니까?
내 XHTML 문서가 완전히 유효하지 않습니다. 그래서 사용하고 싶었습니다. 내 프로젝트에서 어떻게 사용합니까? 내 프로젝트는 C #입니다.
먼저 HTMLAgilityPack 너겟 패키지를 프로젝트에 설치하십시오 .
그런 다음 예를 들면 다음과 같습니다.
HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
// There are various options, set as needed
htmlDoc.OptionFixNestedTags=true;
// filePath is a path to a file containing the html
htmlDoc.Load(filePath);
// Use: htmlDoc.LoadHtml(xmlString); to load from a string (was htmlDoc.LoadXML(xmlString)
// ParseErrors is an ArrayList containing any errors from the Load statement
if (htmlDoc.ParseErrors != null && htmlDoc.ParseErrors.Count() > 0)
{
// Handle any parse errors as required
}
else
{
if (htmlDoc.DocumentNode != null)
{
HtmlAgilityPack.HtmlNode bodyNode = htmlDoc.DocumentNode.SelectSingleNode("//body");
if (bodyNode != null)
{
// Do something with bodyNode
}
}
}
(주의 :이 코드는 예시 일 뿐이며 반드시 최상의 / 유일한 접근 방식은 아닙니다. 자신의 애플리케이션에서 맹목적으로 사용하지 마십시오.)
이 HtmlDocument.Load()
메서드는 또한 .NET 프레임 워크의 다른 스트림 지향 클래스와 통합하는 데 매우 유용한 스트림을 허용합니다. HtmlEntity.DeEntitize()
html 엔티티를 올바르게 처리 하는 또 다른 유용한 방법입니다. (매튜에게 감사합니다)
HtmlDocument
그리고 HtmlNode
가장 많이 사용할 수업입니다. XML 파서와 유사하게 XPath 식을 허용하는 selectSingleNode 및 selectNodes 메서드를 제공합니다.
HtmlDocument.Option??????
부울 속성에 주의하십시오 . 이는 Load
및 LoadXML
메소드가 HTML / XHTML을 처리 하는 방법을 제어합니다 .
또한 각 개체에 대한 완전한 참조가있는 HtmlAgilityPack.chm이라는 컴파일 된 도움말 파일이 있습니다. 일반적으로 솔루션의 기본 폴더에 있습니다.
이것이 당신에게 어떤 도움이 될지 모르겠지만, 나는 기본을 소개하는 몇 가지 기사를 썼습니다.
The next article is 95% complete, I just have to write up explanations of the last few parts of the code I have written. If you are interested then I will try to remember to post here when I publish it.
HtmlAgilityPack uses XPath syntax, and though many argues that it is poorly documented, I had no trouble using it with help from this XPath documentation: https://www.w3schools.com/xml/xpath_syntax.asp
To parse
<h2>
<a href="">Jack</a>
</h2>
<ul>
<li class="tel">
<a href="">81 75 53 60</a>
</li>
</ul>
<h2>
<a href="">Roy</a>
</h2>
<ul>
<li class="tel">
<a href="">44 52 16 87</a>
</li>
</ul>
I did this:
string url = "http://website.com";
var Webget = new HtmlWeb();
var doc = Webget.Load(url);
foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//h2//a"))
{
names.Add(node.ChildNodes[0].InnerHtml);
}
foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//li[@class='tel']//a"))
{
phones.Add(node.ChildNodes[0].InnerHtml);
}
Main HTMLAgilityPack related code is as follows
using System;
using System.Net;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using System.Text.RegularExpressions;
using HtmlAgilityPack;
namespace GetMetaData
{
/// <summary>
/// Summary description for MetaDataWebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class MetaDataWebService: System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(UseHttpGet = false)]
public MetaData GetMetaData(string url)
{
MetaData objMetaData = new MetaData();
//Get Title
WebClient client = new WebClient();
string sourceUrl = client.DownloadString(url);
objMetaData.PageTitle = Regex.Match(sourceUrl, @
"\<title\b[^>]*\>\s*(?<Title>[\s\S]*?)\</title\>", RegexOptions.IgnoreCase).Groups["Title"].Value;
//Method to get Meta Tags
objMetaData.MetaDescription = GetMetaDescription(url);
return objMetaData;
}
private string GetMetaDescription(string url)
{
string description = string.Empty;
//Get Meta Tags
var webGet = new HtmlWeb();
var document = webGet.Load(url);
var metaTags = document.DocumentNode.SelectNodes("//meta");
if (metaTags != null)
{
foreach(var tag in metaTags)
{
if (tag.Attributes["name"] != null && tag.Attributes["content"] != null && tag.Attributes["name"].Value.ToLower() == "description")
{
description = tag.Attributes["content"].Value;
}
}
}
else
{
description = string.Empty;
}
return description;
}
}
}
public string HtmlAgi(string url, string key)
{
var Webget = new HtmlWeb();
var doc = Webget.Load(url);
HtmlNode ourNode = doc.DocumentNode.SelectSingleNode(string.Format("//meta[@name='{0}']", key));
if (ourNode != null)
{
return ourNode.GetAttributeValue("content", "");
}
else
{
return "not fount";
}
}
Getting Started - HTML Agility Pack
// From File
var doc = new HtmlDocument();
doc.Load(filePath);
// From String
var doc = new HtmlDocument();
doc.LoadHtml(html);
// From Web
var url = "http://html-agility-pack.net/";
var web = new HtmlWeb();
var doc = web.Load(url);
try this
string htmlBody = ParseHmlBody(dtViewDetails.Rows[0]["Body"].ToString());
private string ParseHmlBody(string html)
{
string body = string.Empty;
try
{
var htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(html);
var htmlBody = htmlDoc.DocumentNode.SelectSingleNode("//body");
body = htmlBody.OuterHtml;
}
catch (Exception ex)
{
dalPendingOrders.LogMessage("Error in ParseHmlBody" + ex.Message);
}
return body;
}
참고URL : https://stackoverflow.com/questions/846994/how-to-use-html-agility-pack
'your programing' 카테고리의 다른 글
정수의 최대 값 및 최소값 (0) | 2020.10.02 |
---|---|
Java에서 equals 및 hashCode를 재정의 할 때 고려해야 할 문제는 무엇입니까? (0) | 2020.10.02 |
static_cast를 사용하는 이유 (0) | 2020.10.02 |
임시 테이블이 존재하는지 확인하고 존재하는지 삭제 한 후 임시 테이블을 생성합니다. (0) | 2020.10.02 |
유용한 휘발성 키워드는 무엇입니까 (0) | 2020.10.02 |