HTML Agility Packの使用方法を教えてください。
XHTML ドキュメントが完全に有効ではありません。だからこそ使いたかった。プロジェクトでどのように使用するのですか? 私のプロジェクトは C# です。
HTML Agility Packの使用方法を教えてください。
XHTML ドキュメントが完全に有効ではありません。だからこそ使いたかった。プロジェクトでどのように使用するのですか? 私のプロジェクトは C# です。
まず、HTMLAgilityPack nuget パッケージをプロジェクトにインストールします。
次に、例として:
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 フレームワークの他のストリーム指向クラスとの統合に非常に役立つストリームも受け入れます。WhileHtmlEntity.DeEntitize()
は、html エンティティを正しく処理するためのもう 1 つの便利な方法です。(ありがとうマシュー)
HtmlDocument
とHtmlNode
は、最もよく使用するクラスです。XML パーサーと同様に、XPath 式を受け入れる selectSingleNode および selectNodes メソッドを提供します。
HtmlDocument.Option??????
ブール値のプロパティに注意してください。これらは、Load
およびLoadXML
メソッドが HTML/XHTML を処理する方法を制御します。
また、HtmlAgilityPack.chm というコンパイル済みのヘルプ ファイルもあり、各オブジェクトの完全なリファレンスが含まれています。これは通常、ソリューションのベース フォルダーにあります。
参考になるかどうかわかりませんが、基礎を紹介する記事をいくつか書きました。
次の記事は 95% 完了しています。あとは、私が書いたコードの最後のいくつかの部分の説明を書き上げるだけです。興味があれば、公開するときにここに投稿することを忘れないようにします。
主な HTMLAgilityPack 関連のコードは次のとおりです。
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;
}
}
}