簡體   English   中英

將正則表達式轉換為HtmlAgilityPack C#

[英]Regex to HtmlAgilityPack C#

我想知道如何將使用正則表達式的代碼轉換為與使用HtmlAgilityPack庫的其他網站中的字符串匹配的代碼。

示例代碼:

<div class="element"><div class="title"><a href="127.0.0.1" title="A.1">A.1</a></div></div>
<div class="element"><div class="title"><a href="127.0.0.1" title="A.2">A.2</a></div></div>

我當前的代碼如下:

List<string> Cap = new List<string>();
WebClient web = new WebClient();
string url = web.DownloadString("127.0.0.1");
MatchCollection cap = Regex.Matches(url, "title=\"(.+?)\">", RegexOptions.Singleline);
foreach (Match m in cap)
{
     Cap.Add(m.Groups[1].Value.ToString());
}
lst_Cap.ItemsSource = Cap;

而且有效。

我已經嘗試過使用HtmlAgilityPack:

HtmlDocument Web = web.Load("127.0.0.1"); // 127.0.0.1 for example
List<string> Cap = new List<string>();
foreach (HtmlNode node in Web.DocumentNode.SelectNodes("//*[@id=\"content\"]/div/div[3]/div[2]/div[1]/a"))
{
    Cap.Add(node.InnerHtml);
}

但它僅添加A.1。

我能怎么做?

您的正則表達式"title=\\"(.+?)\\">"匹配並捕獲HTML文檔內任何標簽中的任何title屬性。

因此,使用另一個帶有//*[@title] XPath的代碼,該代碼獲取包含title屬性的任何元素節點( * ),然后僅遍歷屬性節點,一旦其名稱為title ,則將值添加到列表中:

var nodes = Web.DocumentNode.SelectNodes("//*[@title]");
if (nodes != null)
{
   foreach (var node in nodes)
   {
       foreach (var attribute in node.Attributes)
           if (attribute.Name == "title")
               Cap.Add(attribute.Value);
   }
}

或使用LINQ:

var nodes = Web.DocumentNode.SelectNodes("//*[@title]");
var res = nodes.Where(p => p.HasAttributes)
                 .Select(m => m.GetAttributeValue("title", string.Empty))
                 .Where(l => !string.IsNullOrEmpty(l))
                 .ToList();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM