在使用InnerText时阻止HTMLAgilityPack连接单词(Prevent HTMLAgilityPack from connecting words when using InnerTex

编程入门 行业动态 更新时间:2024-10-28 10:22:09
在使用InnerText时阻止HTMLAgilityPack连接单词(Prevent HTMLAgilityPack from connecting words when using InnerText)

我正在尝试从HTML文档中获取文本的简单任务。 所以我使用HTMLdoc.DocumentNode.InnerText。 问题是,在一些网站上,当它们位于不同的标签中时,不会在单词之间放置空格。 在这些情况下,DocumentNode.InnerText将这些单词连接成一个,变得毫无用处。

例如,我试图读取包含该行的网站

<span>İstanbul</span><ul><li><a href="i1.htm">Adana</a></li>

我得到了“İstanbulAdana”,这是毫无意义的。

我无法在HTMLAgilityPack文档或Google上找到任何解决方案

我错过了什么吗?

谢谢,

I'm trying to do a simple task of getting text from HTML document. So I'm using HTMLdoc.DocumentNode.InnerText for that. The problem is that on some sites the don't put spaces between words when they are in a different tags. In those cases the DocumentNode.InnerText connect those word into one and it became useless.

for example, I'm trying to read a site contain that line

<span>İstanbul</span><ul><li><a href="i1.htm">Adana</a></li>

I'm getting "İstanbulAdana" which is meaningless.

I couldn't find any solution at HTMLAgilityPack documentation nor Google

Do I missing something?

Thanks,

最满意答案

这应该很容易做到。

const string html = @"<span>İstanbul</span><ul><li><a href=""i1.htm"">Adana</a></li>"; var doc = new HtmlDocument(); doc.LoadHtml(html); string result = string.Join(" ", doc.DocumentNode.Descendants() .Where(n => !n.HasChildNodes && !string.IsNullOrWhiteSpace(n.InnerText)) .Select(n => n.InnerText)); Console.WriteLine(result); // prints "İstanbul Adana"

That should be rather easy to do.

const string html = @"<span>İstanbul</span><ul><li><a href=""i1.htm"">Adana</a></li>"; var doc = new HtmlDocument(); doc.LoadHtml(html); string result = string.Join(" ", doc.DocumentNode.Descendants() .Where(n => !n.HasChildNodes && !string.IsNullOrWhiteSpace(n.InnerText)) .Select(n => n.InnerText)); Console.WriteLine(result); // prints "İstanbul Adana"

更多推荐

本文发布于:2023-04-28 08:26:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1330942.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:单词   HTMLAgilityPack   InnerText   words   connecting

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!