简体   繁体   English

如何获取值href值而不是锚标记?

[英]How to get the values href values rather than the anchor tags?

I've just gotten started with HtmlAgilityPack and I've run into an issue. 我刚开始使用HtmlAgilityPack,但遇到了一个问题。 My code is: 我的代码是:

var urls = html.DocumentNode.SelectNodes("//a[contains(@href, 'watch?v=')");

Currently I'm getting returned an array of anchor tags. 目前,我正在返回锚标签数组。 The thing is that I'd like to get returned an array of strings instead (each containing the href value of the anchor tag). 问题是我想返回一个字符串数组(每个字符串都包含anchor标记的href值)。 How would I do this? 我该怎么做?

Btw I know I could loop through them all afterwards and get the hrefs but I'd like to do this in one line through Xpath. 顺便说一句,我知道以后可以遍历它们并获取href,但是我想通过Xpath在一行中完成此操作。

var urls = html.DocumentNode.SelectNodes("//a[contains(@href, 'watch?v=')")
            .Select(a => a.Attributes["href"].Value)
            .ToList();

The expression you're looking for is 您要寻找的表情是

//a[contains(@href, 'watch?v=')]/@href

selecting the "href" attribute of the a links matching your condition 选择符合您条件a链接的“ href”属性


Edit: Apparently HtmlAgility Pack does NOT support that: Selecting attribute values with html Agility Pack 编辑:显然HtmlAgility Pack不支持该功能: 使用html Agility Pack选择属性值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM