【问题标题】:How do I save a webpage using C++? Windows or Linux System如何使用 C++ 保存网页? Windows 或 Linux 系统
【发布时间】:2015-04-09 19:34:11
【问题描述】:

我需要知道如何在 Windows 和/或 Linux 上使用 C++ 保存网页。

第 1 步)这是我当前打开网页的代码:

ShellExecute(NULL, "open", websiteURL, NULL, NULL, SW_SHOWNORMAL);

第 2 步)这是我将打开的网页保存为 .txt 的步骤

Your help here.

第 3 步)这是我在将网页另存为 .txt 后关闭网页的尝试;但是,它目前不起作用。

ShellExecute(NULL, "close", websiteURL, NULL, NULL, SW_SHOWNORMAL);

【问题讨论】:

  • @Slizzered 是的,涉及 curl,这项工作可以轻松完成。
  • 我自己会打电话给SaveWebPageToDisk(char *url, char *savePath);
  • @mah 如何使用 SaveWebPageToDisk?你能提供更多关于如何设置的细节吗? SaveWebPageToDisk() 的实际定义是什么?

标签: c++ browser save webpage download


【解决方案1】:

这是 Windows 版本。注意,Windows 函数是 Unicode UTF-16,但输出文件可以是 ANSI 或 UTF-8。

#include <iostream>
#include <string>
#include <fstream>
#include <Windows.h>
#include <WinINet.h>

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

int main()
{
    std::ofstream fout(L"c:\\test\\_test.htm", std::ios::binary);
    std::wstring url = L"https://www.stackoverflow.com/questions/29547368";
    HINTERNET hopen = InternetOpen(L"MyAppName", 
                            INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
    if(hopen)
    {
        DWORD flags = INTERNET_FLAG_DONT_CACHE;
        if(url.find(L"https://") == 0) 
            flags |= INTERNET_FLAG_SECURE;
        HINTERNET hinternet = InternetOpenUrl(hopen, url.c_str(), NULL, 0, flags, 0);
        if(hinternet)
        {
            char buf[1024];
            DWORD received = 0;
            while(InternetReadFile(hinternet, buf, sizeof(buf), &received))
            {
                if(!received) break;
                fout.write(buf, received);
            }
            InternetCloseHandle(hinternet);
        }
        InternetCloseHandle(hopen);
    }
    return 0;
}

【讨论】:

  • 我尝试编译此代码并收到以下错误。 {$ g++ test.cpp test.cpp: In function ‘int main()’: test.cpp:57:23: error: ‘printf’ is not declared in this scope printf(src.c_str()); }
  • 我把它改成了cout并添加了头文件&lt;iostream&gt;
  • @bamrak-shemirani 我是否缺少库,本地文件夹中的标题?编译时出现以下错误: $ g++ test.cpp /tmp/ccVUR0Zt.o:test.cpp:(.text+0x72): undefined reference to WinHttpOpen' /tmp/ccVUR0Zt.o:test.cpp:(.text+0x72): relocation truncated to fit: R_X86_64_PC3 2 against undefined symbol WinHttpOpen'
  • 我用 Visual Studio 编译了这段代码,我感觉如果不做很多修改它就不会在 gcc 上运行。也许 gcc 有不同的解决方案。
  • @bamrak-shemirani 我刚刚用 Visual Studio 成功编译并运行了它。它似乎已将 HTML 代码复制到我的控制台。是否可以修改它,使其简单地将网页内容“另存为”作为“.txt”到请求的文件夹?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-30
  • 1970-01-01
  • 2018-05-15
  • 1970-01-01
  • 2020-07-27
相关资源
最近更新 更多