我有一个包含多个div的html文档。
示例:
<div class="element">
<div class="title">
<a href="127.0.0.1" title="Test>Test</a>
</div>
</div>
现在我使用这段代码来提取title元素。
List<string> items = new List<string>();
var nodes = Web.DocumentNode.SelectNodes("//*[@title]");
if (nodes != null)
{
foreach (var node in nodes)
{
foreach (var attribute in node.Attributes)
if (attribute.Name == "title")
items.Add(attribute.Value);
}
}
我不知道如何调整代码以同时提取href和title元素。
每个div应该是一个对象,其中包含一个标记作为属性。
public class CheckBoxListItem
{
public string Text { get; set; }
public string Href { get; set; }
}
发布于 2016-02-15 16:55:41
您可以使用以下xpath查询来检索带有标题和href的标记:
//a[@title and @href]
您可以这样使用您的代码:
List<CheckBoxListItem> items = new List<CheckBoxListItem>();
var nodes = Web.DocumentNode.SelectNodes("//a[@title and @href]");
if (nodes != null)
{
foreach (var node in nodes)
{
items.Add(new CheckBoxListItem()
{
Text = node.Attributes["title"].Value,
Href = node.Attributes["href"].Value
});
}
}
发布于 2016-02-15 17:15:44
我经常将ScrapySharp的包与HtmlAgilityPack一起用于css选择。
(为ScrapySharp.Extensions添加一个using语句,以便您可以使用CssSelect方法)。
using HtmlAgilityPack;
using ScrapySharp.Extensions;
在你的情况下,我会:
HtmlWeb w = new HtmlWeb();
var htmlDoc = w.Load("myUrl");
var titles = htmlDoc.DocumentNode.CssSelect(".title");
foreach (var title in titles)
{
string href = string.Empty;
var anchor = title.CssSelect("a").FirstOrDefault();
if (anchor != null)
{
href = anchor.GetAttributeValue("href");
}
}
https://stackoverflow.com/questions/35414513
复制相似问题