如何阅读在C#中的网站内容? [英] How to read the Website content in c#?

查看:88
本文介绍了如何阅读在C#中的网站内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想读不带HTML标签和标题的网站的文字。我只是需要在Web浏览器中显示的文本。

I want to read the website text without html tags and headers. i just need the text displayed in the web browser.

我不需要这样的

<html>
<body>
bla bla </td><td>
bla bla 
<body>
<html>

我只需要文本喇嘛唧唧歪歪。

我已经使用了Web客户端和HttpWebRequest的方法来获取HTML内容和分割所接收的数据,但是,因为如果我改变网站是不可能标签可能会改变。

I have used the webclient and httpwebrequest methods to get the HTML content and to split the received data but it is not possible because if i change the website the tags may change.

那么,有没有办法让只在网站anagrammatically?

So is there any way to get only the displayed text in the website anagrammatically?

推荐答案

下面是你将如何使用 HtmlAgilityPack 做到这一点。

Here is how you would do it using the HtmlAgilityPack.

首先您的样本HTML:

First your sample HTML:

var html = "<html>\r\n<body>\r\nbla bla </td><td>\r\nbla bla \r\n<body>\r\n<html>";



加载它(如在这种情况下,字符串):

Load it up (as a string in this case):

var doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(html);

如果从网络上获得它,相似的:

If getting it from the web, similar:

var web = new HtmlWeb();
var doc = web.Load(url);

现在选择具有非空白仅文本节点和修剪它们。

Now select only text nodes with non-whitespace and trim them.

var text = doc.DocumentNode.Descendants()
              .Where(x => x.NodeType == HtmlNodeType.Text && x.InnerText.Trim().Length > 0)
              .Select(x => x.InnerText.Trim());

如果你喜欢,你可以得到这个作为一个单一的加入字符串:

You can get this as a single joined string if you like:

String.Join(" ", text)

当然,这将只简单的网页的工作。任何复杂的也将返回的数据节点,你显然不希望,如JavaScript函数等。

Of course this will only work for simple web pages. Anything complex will also return nodes with data you clearly don't want, such as javascript functions etc.

这篇关于如何阅读在C#中的网站内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆