【发布时间】:2017-04-09 14:04:21
【问题描述】:
我正在尝试从此 HTML 标记中提取文本
<span id="example1">sometext</span>
我有这个代码:
using System;
using System.Net;
using HtmlAgilityPack;
namespace GC_data_console
{
class Program
{
public static void Main(string[] args)
{
using (var client = new WebClient())
{
// Download the HTML
string html =
client.DownloadString("https://www.requestedwebsite.com");
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(html);
foreach(HtmlNode link in
doc.DocumentNode.SelectNodes("//span"))
{
HtmlAttribute href = link.Attributes["id='example1'"];
if (href != null)
{
Console.WriteLine(href.Value.ToString());
Console.ReadLine();
}
}
}
}
}
}
但我仍然没有收到 sometext 的文字。
但如果我插入:
HtmlAttribute href = link.Attributes["id"];
我会得到所有的 ID 名称。我做错了什么?
【问题讨论】:
-
您能否分享您尝试获取内容的实际 URL?此外,您正在尝试获取
HtmlAttribute的值而不是元素。你需要尝试得到的是link.InnerText。 -
你好,例如从这个网页geocaching.com/geocache/GC257YR_slivercup-studios-east,我正在尝试从标签中获取文本:SliverCup Studios East
-
知道了.... 你试过我建议的其他方法了吗?您是否还调试并检查您是否获得了正确的元素?
-
我试过了,HtmlAttribute href = link.InnerText["id='ctl00_ContentBody_CacheName'"];但它没有用,我得到参数 1:无法将类型 'int' 隐式转换为 'string' (CS1503) 错误