A. *_*Kim 2 c++ special-characters web-scraping
我正在尝试获取Barack Obama的Wikipedia页面的源代码并将其保存到文件中。
一切正常,直到我打开文件并在其中看到一些奇怪的字符:
如您所见,它EOT1024出现在文件中,但是没有出现在网站的实际源代码中(我使用Google Chrome浏览器检查过)。我想知道为什么会发生这种情况,以及如何阻止这种情况发生。
我的代码:
#include <iostream>
#include <windows.h>
#include <wininet.h>
#include <fstream>
int main(){
std::string textLink = "https://en.wikipedia.org/wiki/Barack_Obama";
std::ofstream file;
HINTERNET hInternet, hFile;
char buf[1024];
DWORD bytes_read;
int finished = 0;
bool e=false;
std::string waste;
file.open("data.txt",std::ios::out);
hInternet = InternetOpenW(L"Whatever", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
if (hInternet == NULL) {
printf("InternetOpen failed\n");
}
hFile = InternetOpenUrl(hInternet, textLink.c_str(), NULL, 0L, 0, 0);
if (hFile == NULL) {
printf("InternetOpenUrl failed\n");
}
while (!finished) {
if (InternetReadFile(hFile, buf, sizeof(buf), &bytes_read)) {
if (bytes_read > 0) {
file << bytes_read << buf;
}
else {
finished = 1;
}
}
else {
printf("InternetReadFile failed\n");
finished = 1;
}
}
InternetCloseHandle(hInternet);
InternetCloseHandle(hFile);
file.close();
}
Run Code Online (Sandbox Code Playgroud)
我在这里在记事本中查看文本文件:
https://drive.google.com/open?id=1Ty-a1o29RWSQiO1zTLym6XH4dJvUjpTO
我不明白为什么我会在data.txt写入的文件中得到这些字符。
注:偶尔,而不是看到EOT1024,我甚至得到EOT21,EOT1016以及其他看似随机字符。
您实际上是在将整数写入bytes_read文件:
file << bytes_read << buf;
Run Code Online (Sandbox Code Playgroud)
有您的“ 1024”(有时会读取1024个字节)。
不要那样做
此外,您似乎buf以null终止。相反,流的第一bytes_read的buf; 这就是为什么你有那个整数。
所以:
file.write(&buf[0], bytes_read);
Run Code Online (Sandbox Code Playgroud)
请查阅文档:
普通读取将为每次InternetReadFile的调用检索指定的dwNumberOfBytesToRead,直到到达文件末尾。为了确保检索到所有数据,应用程序必须继续调用InternetReadFile函数,直到该函数返回TRUE并且lpdwNumberOfBytesRead参数等于零为止。