我正在使用Html Agility Pack并尝试从以下html代码中提取链接和链接文本。网页从远程页面获取,并作为整体保存在本地。然后从这个本地网页我试图提取链接和链接文本。该网页在其页面内自然有其他html代码,如其他链接文本等,但为了清楚起见,此处将其删除。
<span class="Subject2"><a href="/some/today.nsf/0/EC8A39D274864X5BC125798B0029E305?open">
Description 1 text here</span> <span class="time">2012-01-20 08:35</span></a><br>
<span class="Subject2"><a href="/some/today.nsf/0/EC8A39XXXX264X5BC125798B0029E312?open">
Description 2 text here</span> <span class="time">2012-01-20 09:35</span></a><br>
但是,以上是尝试提取链接和链接文本时最常用的内容。
这就是我希望看到的结果
<link>/some/today.nsf/0/EC8A39D274864X5BC125798B0029E305</link>
<title>Description 1 text here</title>
<pubDate>Wed, 20 Jan 2012 07:35:00 +0100</pubDate>
<link>/some/today.nsf/0/ EC8A39XXXX264X5BC125798B0029E312</link>
<title>Description 2 text here</title>
<pubDate> Wed, 20 Jan 2012 08:35:00 +0100</pubDate>
到目前为止,这是我的代码:
var linksOnPage = from lnks in document.DocumentNode.SelectNodes("//span[starts-with(@class, 'Subject2')]")
(lnks.Name == "a" &&
lnks.Attributes["href"] != null &&
lnks.InnerText.Trim().Length > 0)
select new
{
Url = lnks.Attributes["href"].Value,
Text = lnks.InnerText
Time = lnks. Attributes["time"].Value
};
foreach (var link in linksOnPage)
{
// Loop through.
Response.Write("<link>" + link.Url + "</link>");
Response.Write("<title>" + link.Text + "</title>");
Response.Write("<pubDate>" + link.Time + "</pubDate>");
}
它没有用,我什么也没得到。
所以任何建议和帮助都将受到高度赞赏。
提前致谢。
更新:我已设法立即获取语法,以便从上面的示例中选择链接:使用以下代码:
var linksOnPage = from lnks in document.DocumentNode.SelectNodes("//span[@class='Subject2']//a")
这会很好地选择与网址和文字相关的链接,但如何获取时间戳呢?
即,选择此时间戳:
<span class="time">2012-01-20 09:35</span></a>
每个链接后面的。根据以上内容,输出循环内的每个链接都有输出?感谢您对此提供任何帮助。
答案 0 :(得分:0)
您的HTML示例格式不正确,这就是您获得意外结果的原因。
要找到您的第一个和第二个值,您必须在<a>
中获得<span class='Subject2'>
- 第一个值是href
属性值,第二个值是{{1}锚的锚。要获得第三个值,您必须获得InnerText
标记的以下兄弟并获取其<span class='Subject2'>
。
请参阅,如何做到这一点:
InnerText
这输出类似:
var nodes = document.DocumentNode.SelectNodes("//span[@class='Subject2']//a");
foreach (var node in nodes)
{
if (node.Attributes["href"] != null)
{
var link = new XElement("link", node.Attributes["href"].Value);
var description = new XElement("description", node.InnerText);
var timeNode = node.SelectSingleNode(
"..//following-sibling::span[@class='time']");
if (timeNode != null)
{
var time = new XElement("pubDate", timeNode.InnerText);
Response.Write(link);
Response.Write(description);
Response.Write(time);
}
}
}