【问题标题】:How to extract span value from html using xpath in c#?如何在 c# 中使用 xpath 从 html 中提取跨度值?
【发布时间】:2017-10-31 20:01:26
【问题描述】:
  1. 我遇到了一个问题,我只想从 x-path 属性中提取数据 选择器这是要显示的内部文本的 div 和 span 请帮助我 出去。
  2. 我还在 for each 循环中执行了 16 次此选项。

    <div class="l">
    <span id="ls_title_7596012" class="ls_h_desc" title="Required 10 marla 
    old house in any block of bahria town">Required 10 marla old house in 
    any block of bahria town</span>
    </div>
    
  3. 我也在尝试这个,但没有成功。

     var name=htmlDocument?.DocumentNode?.SelectNodes("//div[@class=\"1\"]//span[@class=\"ls_h_desc\"]//title")[0].InnerText;
    

【问题讨论】:

    标签: c# html xpath


    【解决方案1】:

    试试这个,如果需要获取“title”属性值:

    var title = htmlDocument.DocumentNode.SelectSingleNode("//*[@id = 'ls_title_7596012]'").getAttribute("title").value
    

    var title = htmlDocument.DocumentNode.SelectSingleNode("//*[@id = 'ls_title_7596012]/@title'")
    

    如果您需要获取内部文本,您可以尝试:

    var text = htmlDocument.DocumentNode.SelectSingleNode("//*[@id = 'ls_title_7596012]'").InnerText
    

    var text = htmlDocument.DocumentNode.SelectSingleNode("//*[@id = 'ls_title_7596012]/text()'").InnerText
    

    【讨论】:

    • 这会给我一个静态值在 1 次以上的问题我说需要这些值在 16 次在这个标签中也感谢你的建议
    • 如果这16次“Id”属性不同,可以使用“class”属性,如果每次都相同var text = htmlDocument.DocumentNode.SelectSingleNode("//*[@class = 'ls_h_desc']").InnerTextvar title = htmlDocument.DocumentNode.SelectSingleNode("//*[@class = 'ls_h_desc']").getAttribute("title").value
    【解决方案2】:

    我更喜欢将 HtmlAgilityPack 与 css 选择器一起使用。有一个包做这个工作https://github.com/hcesar/HtmlAgilityPack.CssSelector

    [TestFixture]
    public class TestClass
    {
        [Test]
        public void TestMethod()
        {
    
    
        var html = @"<div class=""l"">
    <span id=""ls_title_7596012"" class=""ls_h_desc"" title=""Required 10 marla 
    old house in any block of bahria town"">Required 10 marla old house in 
    any block of bahria town</span>
    </div>";
    
            // Try HtmlAgilityPack with css selector
            var doc = new HtmlAgilityPack.HtmlDocument();
            doc.LoadHtml(html);
    
            IList<HtmlNode> nodes = doc.QuerySelectorAll("div.l #ls_title_7596012");
            Assert.IsNotEmpty(nodes);
            Assert.AreEqual(nodes.First().InnerText, "Required 10 marla old house in \r\nany block of bahria town");
    
    
            // try with xpath
            var xpath = @"//*[@id=""ls_title_7596012""]";
            nodes = doc.DocumentNode.SelectNodes(xpath);
            Assert.IsNotEmpty(nodes);
            Assert.AreEqual(nodes.First().InnerText, "Required 10 marla old house in \r\nany block of bahria town");
        }
    }
    

    【讨论】:

    • 我也使用带有 x 路径的 HtmlAgility Pack 但没有成功
    猜你喜欢
    • 2016-04-15
    • 1970-01-01
    • 2019-08-31
    • 2020-07-22
    • 1970-01-01
    • 1970-01-01
    • 2015-07-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多