c# - 从 HTML 字符串中提取 HREF 值
问题描述
我正在尝试创建一个只返回来自网站的链接的爬虫,并且我让它返回 HTML 脚本。我现在想使用 if 语句来检查字符串是否返回,如果返回,它会搜索所有“< a >”标签并向我显示 href 链接。但我不知道要检查什么对象或应该检查什么值。
这是我到目前为止所拥有的:
namespace crawler
{
class Program
{
static void Main(string[] args)
{
System.Net.WebClient wc = new System.Net.WebClient();
string WebData wc.DownloadString("https://www.abc.net.au/news/science/");
Console.WriteLine(WebData);
// if
}
}
}
解决方案
你可以看看HTML Agility Pack:
然后,您可以从网页中找到所有链接,例如:
var hrefs = new List<string>();
var hw = new HtmlWeb();
HtmlDocument document = hw.Load(/* your url here */);
foreach(HtmlNode link in document.DocumentNode.SelectNodes("//a[@href]"))
{
HtmlAttribute attribute = link.Attributes["href"];
if (!string.IsNullOrWhiteSpace(attribute.Value))
hrefs.Add(attribute.Value);
}
推荐阅读
- elasticsearch - 如何根据字段值将一个索引复制到多个索引中?
- audit-logging - 审核的排除过滤器增加了显着的延迟
- google-cloud-platform - 谷歌云计算虚拟机实例未列出
- excel - 如何使用来自 WorksheetFunction.Unique() 的值填充数组?
- mysql - 创建配方数据库时,如何将 recipe_ID 与多个成分 ID 实例链接?
- c# - 将 DataRow 与其他 DataRow 进行比较
- pandas - 如何将 seaborn 的 catplot 绘制到 gridspec
- java - 扫描仪正在跳过一行并转到下一行
- r - 如何从匹配条件的行之后的行中返回一个值?
- r - R2jags :: JAGS“初始化模型”