获取网页信息源码后如何取自己想要的内容
如:我用WebClient把news.sina.com.cn这个页的右键源代码全部保存下来了。现在想把里面的新闻标题全部获取到,有啥快速办法,效率有高。
[解决办法]
正则、HtmlAgilityPack
[解决办法]
问题:如何从字符串中按一定的规则找到自己所需要的内容
参考答案:正则表达式
[解决办法]
mark一下,说不定以后我也为这个犯愁,有备无患总是好的
[解决办法]
如果说你可以添加一个winform窗口,在窗口上拖入一个webbrowser控件,然后编写网页分析代码,例如
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (this.webBrowser1.ReadyState == WebBrowserReadyState.Complete && this.找到啦 != null)
{
var element = this.webBrowser1.Document.GetElementById("syncad_0");
var result = from li in element.Children.OfType<HtmlElement>()
where li.TagName == "LI"
from a in li.Children.OfType<HtmlElement>()
where a.TagName == "A"
select new ResultType
{
href = a.GetAttribute("href"),
text = a.InnerText
};
this.找到啦(result.ToList());
}
}
private void Form1_Load(object sender, EventArgs e)
{
this.webBrowser1.Navigate("http://www.sina.com.cn/");
}
public class ResultType
{
public string href;
public string text;
}
public event Action<List<ResultType>> 找到啦;
}
}
[解决办法]
任何一个Html分析器都是如此,也就是代码
var element = this.webBrowser1.Document.GetElementById("syncad_0");
var result = from li in element.Children.OfType<HtmlElement>()
where li.TagName == "LI"
from a in li.Children.OfType<HtmlElement>()
where a.TagName == "A"
select new ResultType
{
href = a.GetAttribute("href"),
text = a.InnerText
};
这个准确而轻松的表达式即可。
[解决办法]
HtmlAgilityPack 的代码留给别人来给你写吧,它要比webbrowser更快、、更干净、更简单(比如说不需要处理浏览器异常信息等等)!