using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SHDocVw;//System32/SHDocVw.dll
using mshtml;
using System.Threading;
using System.Diagnostics;//microsoft.mshtmlnamespace CollectBase
{ public class MockIE
{
private InternetExplorer ie = new InternetExplorer();
/// <summary>
/// IE读取网页
/// </summary>
/// <param name="url">需要访问的Url</param>
/// <returns>返回源代码内容</returns>
public string downLoadFile(string url)
{
string str = ""; ie.Visible = false;
Object nullArg = null;
IHTMLDocument2 DOM;
IHTMLElement e;
try
{
ie.Navigate(url, ref nullArg, ref nullArg, ref nullArg, ref nullArg);
Thread.Sleep(500);//默认时间间隔0.5秒
while (true)//死循环,直到下载文件成功
{
DOM = ie.Document as IHTMLDocument2;
DOM.designMode = "On";
e = DOM.body;//这个地方会报错,报错的内容是:未将对象引用设置到对象的实例。
if (DOM != null)
{
str = e.outerHTML;
int t1 = str.IndexOf("</body>");
int t2 = str.IndexOf("</BODY>");//很笨的办法检测是否下载完成。
if (t1 < 0 && t2 < 0)
{
ie.Navigate(url, ref nullArg, ref nullArg, ref nullArg, ref nullArg);
Thread.Sleep(2000);//没下载成功,时间间隔2秒
}
else break;
}
else
{
ie.Navigate(url, ref nullArg, ref nullArg, ref nullArg, ref nullArg);
Thread.Sleep(2000);
}
}
}
//catch { }
catch (Exception ex)
{
Debug.Print("[Debug]" + "[" + ex.Source + "]" + "[" + ex.InnerException.Source + "]" + ex.Message);
}
if (str == null)
{
return downLoadFile(url);
}
else
{
return str;
}
}
}
}
从IHTMLDocument2取字符串会偶尔报错,从测试中看来,明明IHTMLDocument2对象中有内容,但就是无法读取出来
就是e = DOM.body这句会偶尔出错,也是不全部,所有的URL都来自一个列表,内容差不多的
请高手指教~~~~为何一个赋值,赋值成功率会有偶然性
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货