首页 > 解决方案 > 使用 html 敏捷包获取文本值

问题描述

请检查下面的代码。我正在尝试从此 html 文档中获取 html 文本值。我想抓取文本Quick Kill 32 oz. Mosquito Yard Spray,我已经尝试使用SelectSingleNode如下所示的方法来抓取文本,但无法抓取该文本值。知道如何解决吗?

string html = @"<div class='pod-plp__description js-podclick-analytics' data-podaction='product name'>
    <a class='' data-pos='0' data-request-type='sr' data-pod-type='pr' href='/p/AMDRO-Quick-Kill-32-oz-Mosquito-Yard-Spray-100530440/304755303'>
    <span class='pod-plp__brand-name'>AMDRO</span> 
    Quick Kill 32 oz. Mosquito Yard Spray
    </a>
</div>";

var doc = new HtmlDocument();    
doc.Load(html);

string title = doc.DocumentNode
    .SelectSingleNode("//div[@class='pod-plp__description js-podclick-analytics']span[@class='pod-plp__brand-name']")
    .InnerText;

标签: c#html-agility-pack

解决方案


您正在尝试仅定位只会span[@class='pod-plp__brand-name']在跨度内返回您的目标,但您需要在following-sibling::text()跨度之后获取文本。请在下面查看我的示例代码。您也可以从 html-agility-pack 官方网站了解更多信息。

var Content = htmlDoc.DocumentNode.SelectSingleNode("//span[@class='pod-plp__brand-name']/following-sibling::text()[1]");

string title = titleAgain.InnerText.Trim();

从这里找到解决方案


推荐阅读