今天分享一个c#下使用GeckoWebBrowser的小程序。
写了个小程序用来采集房产网的数据。以前也写过类似的程序,用的.net自带的webbrowser,这家伙好用倒是还可以
步骤如下:
写了个小程序用来采集房产网的数据。以前也写过类似的程序,用的.net自带的webbrowser,这家伙好用倒是还可以
就是占用内存啊,由于是使用的ie内核,清理内存和缓存都没有什么直接办法,而占用内存是这个家伙的硬伤,即使你调用GC几次都不管用的。
这个就不是系统给清理了,应该是IE占用这无法清理。
步骤如下:
项目开源地址:http://code.google.com/p/geckofx/
flash插件下载地址: http://get.adobe.com/flashplayer/otherversions/
你能够在MDC上的
XULRunner主页中找到下载连接.
支持Windows版本的XULRunner是一个zip文件, 并不是一个真正的安装程序. 作为一个开发人员, 我喜欢XULRunner的这个方式, 只需要解压缩到我的机器中.
为了方便部署,可以解压到开发项目的目录下面。
2.下载C# Skybound.Gecko源代码:
编译时如果报错,需要选择bug版本到1.90的。这个地方尤为重要。如果还是报错,那就把你的项目改成x86的。
3.新建项目:

引用 Skybound.Gecko。编译通过
4.初始化浏览器的参数:
xulrunner路径一定要配对,不会报错,叫你去下载:
static private string xulrunnerPath = Application .StartupPath + "\\xulrunner" ;
static
private
string
xulrunnerPath =
Application
.StartupPath +
"\\xulrunner"
;
public
CatchData()
{
InitializeComponent();
InitAllCityData();
}
private
void
InitAllCityData()
{
Skybound.Gecko.
Xpcom
.Initialize(xulrunnerPath);
Browser.DocumentCompleted +=
new
EventHandler
(Browser_DocumentCompleted_Init);
GeckoPreferences
.User[
"gfx.font_rendering.graphite.enabled"
] =
true
;
}
5.几个事件和Html控件:
监控页面是否加载完成:
Browser.DocumentCompleted +=
new
EventHandler
(Browser_DocumentCompleted_Init);
加载完成后,可以读取页面的源代码数据:
void
Browser_DocumentCompleted_Init(
object
sender,
EventArgs
e)
{
GeckoWebBrowser
br = sender
as
GeckoWebBrowser
;
if
(br.Url.ToString() ==
"about:blank"
) {
return
; }
ShowClickMsg(
"开始加载全国的城市数据"
+ br.Url.ToString());
Log
.logger(
"开始加载全国的城市数据"
+ br.Url.ToString());
foreach
(Skybound.Gecko.
GeckoElement
a
in
br.Document.Links)
{
if
(a.Parent !=
null
&&
a.Parent.Parent !=
null
&&
a.Parent.Parent.ClassName !=
null
&&
a.Parent.Parent.ClassName ==
"cBox"
&&
a.Parent.Parent.ClassName !=
null
&&
a.Parent.Parent.Parent.ClassName !=
null
&&
a.Parent.Parent.Parent.ClassName ==
"s_Box_1 hidden"
)
{
if
(!ListCItyUrl.ContainsKey(a.TextContent.Trim()))
{
ShowClickMsg(a.TextContent.Trim() + a.GetAttribute(
"href"
));
ListCItyUrl.Add(a.TextContent.Trim(), a.GetAttribute(
"href"
));
}
}
}
//绑定到下拉框中啊
}
我发现
GeckoWebBrowser
的html元素比较简单,没有webbrowser的那么多分类。
我想找超级链接的类没有找的,老版本的还有,最新的好像去掉了。
控件类有:
GeckoElement 、
GeckoNode。
GeckoWebBrowser
对源代码的解析比webbrowser多很多的\t\n\r之类的。这些垃圾数据需要踢出掉。
6.内存情况
在处理相同数据的页面请求的情况下,
GeckoWebBrowser几乎不会出现内存的大浮动变动。采集4000个页面数据,内存一般在1G的浮动范围内。当然也有内存丢失。关闭程序才能解决。

如何分析得到html,下篇我将讲讲怎么使用