110,532
社区成员
发帖
与我相关
我的任务
分享
private void button2_Click(object sender, EventArgs e)//点击按钮进行过滤测试
{
IHTMLDocument3 HTMLDocument = (IHTMLDocument3)this.webBrowser1.Document.DomDocument;
IHTMLDOMNode rootDomNode = (IHTMLDOMNode)HTMLDocument.documentElement;
IHTMLDOMNode bodyNode = null;
if (rootDomNode.hasChildNodes())
{
IHTMLDOMChildrenCollection allchild = (IHTMLDOMChildrenCollection)rootDomNode.childNodes;
int length = allchild.length;
for (int i = 0; i < length; i++)
{
IHTMLDOMNode child_node = (IHTMLDOMNode)allchild.item(i);
if (string.Equals(child_node.nodeName,"body",StringComparison.OrdinalIgnoreCase))
{
bodyNode = child_node;
break;
}
}
}
ArrayList del = new ArrayList();
if (bodyNode != null && bodyNode.hasChildNodes())
{
IHTMLDOMChildrenCollection allchild = (IHTMLDOMChildrenCollection)bodyNode.childNodes;
int length = allchild.length;
for (int i = 0; i < length; i++)
{
IHTMLDOMNode child_node = (IHTMLDOMNode)allchild.item(i);
if (string.Equals(child_node.nodeName, "div", StringComparison.OrdinalIgnoreCase))
{
IHTMLDOMNode fix = GetFixedDiv(child_node);
if(fix != null)
{
if (NeedFilter(fix))
{ del.Add(fix); }
}
}
}
for (int i = 0; i < del.Count;++i )
{
IHTMLDOMNode node = (IHTMLDOMNode)del[i];
if (node.hasChildNodes())
{
IHTMLDOMChildrenCollection allchild0 = (IHTMLDOMChildrenCollection)node.childNodes;
int length0 = allchild0.length;
for (int j = 0; j < length0; j++)
{
IHTMLDOMNode child_node = (IHTMLDOMNode)allchild.item(j);
child_node.removeNode(true);
}
}
//if(node.parentNode != null)
//{ node.parentNode.removeChild(node); }
node.removeNode(true);
}
}
}
private IHTMLDOMNode GetFixedDiv(IHTMLDOMNode div)
{
if(div != null)
{
IHTMLStyle style = ((IHTMLElement)div).style;
if (string.Equals("fixed", style.position, StringComparison.OrdinalIgnoreCase))
{
return div;
}
if (div.hasChildNodes())
{
IHTMLDOMChildrenCollection allchild = (IHTMLDOMChildrenCollection)div.childNodes;
int length = allchild.length;
for (int i = 0; i < length; i++)
{
IHTMLDOMNode child_node = (IHTMLDOMNode)allchild.item(i);
if (string.Equals(child_node.nodeName, "div", StringComparison.OrdinalIgnoreCase))
{
IHTMLDOMNode re = GetFixedDiv(child_node);
if(re != null)
{ return re; }
}
}
}
}
return null;
}
private bool NeedFilter(IHTMLDOMNode node)
{
if (node != null && node.hasChildNodes())
{
//this.textBox1.Text += "\n\n";
IHTMLDOMChildrenCollection allchild = (IHTMLDOMChildrenCollection)node.childNodes;
int length = allchild.length;
for (int i = 0; i < length; i++)
{
IHTMLDOMNode child_node = (IHTMLDOMNode)allchild.item(i);
//this.textBox1.Text += (child_node.nodeName + "\n");
if (string.Equals(child_node.nodeName, "img", StringComparison.OrdinalIgnoreCase) ||
string.Equals(child_node.nodeName, "object", StringComparison.OrdinalIgnoreCase) ||
string.Equals(child_node.nodeName, "iframe", StringComparison.OrdinalIgnoreCase))
{
return true;
}
if (NeedFilter(child_node))
{ return true; }
}
}
return false;
}