分享

VC中使用CInternetSession抓取网页内容

 guoliyan1 2012-02-06

VC中使用CInternetSession抓取网页内容

2008-12-09 16:33:54 阅读(660) 发表评论

  在 VC 中用 WinInet 的 CInternetSession::OpenURL(url),得到一个 CFile,读取其中的内容即可,详细代码如下

双击代码全选
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <stdio.h> 
#include <afxinet.h> 
int main(int argc, char* argv[]) 
{ 
  CInternetSession session("HttpClient"); 
  char * url = " http://www./simcard.php?simcard=1392658"; 
  CHttpFile* pfile = (CHttpFile *)session.OpenURL(url); 
  DWORD dwStatusCode; 
  pfile -> QueryInfoStatusCode(dwStatusCode); 
  if(dwStatusCode == HTTP_STATUS_OK) 
  { 
    CString content; 
    CString data; 
    while (pfile -> ReadString(data)) 
    { 
      content += data + "rn"; 
    } 
    content.TrimRight(); 
    printf(" %sn " ,(LPCTSTR)content); 
  }  
  pfile -> Close(); 
  delete pfile; 
  session.Close(); 
  return  0 ; 
} 
#include <stdio.h>
#include <afxinet.h>
int main(int argc, char* argv[])
{
  CInternetSession session("HttpClient");
  CHttpFile* pfile = (CHttpFile *)session.OpenURL(url);
  DWORD dwStatusCode;
  pfile -> QueryInfoStatusCode(dwStatusCode);
  if(dwStatusCode == HTTP_STATUS_OK)
  {
    CString content;
    CString data;
    while (pfile -> ReadString(data))
    {
      content += data + "rn";
    }
    content.TrimRight();
    printf(" %sn " ,(LPCTSTR)content);
  }
  pfile -> Close();
  delete pfile;
  session.Close();
  return  0 ;
}

  其他如不从缓存中读取内容及如何使用代理连接现在就不说了,可以参考下面的链接,或者下次补上。另外不妨看看 Java 是如何读取 URL 内容的,更简单

双击代码全选
1
2
3
4
5
6
7
8
9
10
11
12
13
14
GetMethod httpMethod = new GetMethod("http://unmi."); 
int statusCode = new HttpClient().executeMethod(httpMethod); 
if(statusCode == HttpStatus.SC_OK) 
{ 
  System.out.println(httpMethod.getResponseBodyAsString()); 
} 
httpMethod.releaseConnection(); 
GetMethod httpMethod = new GetMethod("http://unmi.");
int statusCode = new HttpClient().executeMethod(httpMethod);
if(statusCode == HttpStatus.SC_OK)
{
  System.out.println(httpMethod.getResponseBodyAsString());
}
httpMethod.releaseConnection();

  内容取过来之后,总是希望从中拣出需要的数据,可惜 VC6 中没有自己的正则表达式库,所以下一步要学用 boost 的正则表达式库。

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多