初识Wininet:抓网页

本文介绍了一个使用C++实现的简单网页抓取程序。该程序利用Wininet库进行HTTP请求,获取指定URL的内容,并将其保存到本地文件中。通过此示例,读者可以了解到如何使用C++和Windows API来完成基本的网络交互任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include "stdafx.h"
#include<windows.h>
#include<Wininet.h>
#include<iostream>
#include<fstream>
#include<string>

#pragma comment(lib,"WinInet.lib")

using namespace std;

int main()
{
    HINTERNET hINet, hHttpFile;              
    char szSizeBuffer[32];
  
    DWORD dwLengthSizeBuffer = sizeof(szSizeBuffer);
  
    hINet = InternetOpen("IE6.0", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0 );    
 
    string url = "http://www.sina.com";          
    if ( !hINet )
    {
        cout << "InternetOpen fail" << endl;
        return 1;
    }

    hHttpFile = InternetOpenUrl(hINet, url.c_str(), NULL, 0, 0, 0);   

    if(!hHttpFile)
    {
        cout << "error open url" << endl;
        return 1;
    }
  
    BOOL bQuery = HttpQueryInfo(hHttpFile,
                                HTTP_QUERY_CONTENT_LENGTH,
                                szSizeBuffer,
                                &dwLengthSizeBuffer, NULL); 

    if(bQuery ==false)
    {
        InternetCloseHandle(hINet);
        cout << "error query info" << endl;
        return 3;
    }
    int FileSize=atol(szSizeBuffer);   

    string revData;

    revData.resize(FileSize);
  
    DWORD dwBytesRead;

    BOOL bRead = InternetReadFile(hHttpFile, &revData[0], FileSize, &dwBytesRead);   

  
    if(!bRead)
    {
        cout << "error to read file" << endl;
        return 4;
    }

    ofstream   out_file("wangye.txt");  
    out_file << revData;            

    InternetCloseHandle(hHttpFile);
    InternetCloseHandle(hINet);
  
    cout << "capture success !/n" << endl;
    system("pause");
    return 0;
  
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值