以前一直用正则抓取网页,今天用HtmlAgilityPack.dll 向某网站抓取页面信息,但是总是提示:
“服务器提交了协议冲突. Section=ResponseHeader Detail=CR 后面必须是 LF”
代码如下:
“`C#
HtmlWeb htmlweb = new HtmlWeb();
HtmlAgilityPack.HtmlDocument htmldoc = htmlweb.Load(“http://xxxxx”);
HtmlNode rootNode = htmldoc.DocumentNode;
string catpath = “//html/body/table/center[1]/tr[1]/td[2]”;
//关于这里的层次:如果有其它标签,只要不是双标签(
HtmlNodeCollection node = rootNode.SelectNodes(catpath);
string txt = “”;
foreach (var item in node)
{
txt = item.InnerText;//txt就是提取的文字
}
开始以为是dll的方法有问题,然后我用老方法:
```C#
WebClient myWebClient = new WebClient();
byte[] myDataBuffer = myWebClient.DownloadData("http://xxxx");
return Encoding.Default.GetString(myDataBuffer);
依然这个提示,我试试抓取百度页面,果然正常,估计是网站的页面有问题。
查找了相关资料,修改了配置文件解决了:
通过修改配置文件解决:在app.config(WinForm)或web.config(Web)文件里修改。
WinForm下的app.config如果不存在,手动在Debug文件夹所在的同级目录下新建一个XML配置文件,内容为:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.net>
<settings>
<httpWebRequest useUnsafeHeaderParsing= "true " />
</settings>
</system.net>
</configuration>
搞定了。
看到网上还有另一种方法,没试过,记下吧:
方法2:
在DEBUG目录下,新建 项目名.exe.config,比如说QQFarm.exe.config,然后里面输入以上内容:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.net>
<settings>
<httpWebRequest useUnsafeHeaderParsing= "true " />
</settings>
</system.net>
</configuration>
然后编译,出自动在DEBUG目录下生成”项目名.vshost.exe.config”文件。