利用MFC获取网页内容
#include <iostream> #include <ctime> #include <cstring> #include <string> #include <fstream> #include <sstream> #include <cstdlib> #include <afxinet.h> using namespace std; string GetHtml(CString url) { CString content; CString data; DWORD dwStatusCode; CInternetSession session("HttpClient"); CHttpFile* pfile = (CHttpFile *)session.OpenURL(url); pfile -> QueryInfoStatusCode(dwStatusCode); if(dwStatusCode == HTTP_STATUS_OK) { while (pfile -> ReadString(data)) { content += data; } } pfile -> Close(); delete pfile; session.Close(); return string(content.GetBuffer(content.GetLength())); } string GetHtmlPath(int y, int m, int d) { stringstream str; string now; string path = "http://www.nod32jihuoma.cn/nod32-id/"; str << y + 1900; str >> now; path.append(now); path.append("-"); now.clear(); str.clear(); int month = m + 1; if(month / 10 == 0) { str << 0; str >> now; path.append(now); now.clear(); str.clear(); } str << month; str >> now; path.append(now); path.append("-"); now.clear(); str.clear(); int day = d; if(day / 10 == 0) { str << 0; str >> now; path.append(now); now.clear(); str.clear(); } str << day; str >> now; path.append(now); path.append(".html"); now.clear(); str.clear(); return path; } void SearchData(int n) { ofstream cout("key.txt"); const string key = "<div>用户名:";//13 const string value = " 密 码:";//14 time_t t = time(NULL); struct tm* cur = localtime(&t); int y = cur->tm_year; int m = cur->tm_mon; int d = cur->tm_mday; for(int i = 0 ; i < n; i++) { int dd = d - i; string path = GetHtmlPath(y, m, dd); cout << "获取网址" << "\n" << path << endl; CString url; url.Format("%s",path.c_str()); string data = GetHtml(url); //cout << data << endl; cout << y + 1900 << "年" << m + 1 << "月" << dd << "日 " << endl; cout << "用户名: 密码:" <<endl; for(size_t pos = 0; pos < data.size(); pos++) { size_t t = data.find(key,pos); if(t == string::npos) break; t += 13; for(int i = 1; i <= 14; i++,t++) { cout << data[t]; } cout << " "; t += 14; for(int i = 1; i <= 10; i++,t++) { cout << data[t]; } pos = t; cout << endl; } } cout.close(); } int main() { SearchData(2); string str; ifstream fin("key.txt"); while(fin) { getline(fin,str); cout << str << endl; str.clear(); } fin.close(); system("pause"); return 0; }
出现的问题:
1:、不能将参数 1 从“const char [11]”转换为“LPCTSTR”
将项目属性里的字符集改为多字符集即可。
2、Building MFC application with /MD[d] (CRT dll version)requires MFC shared dll version~~~~
将项目属性里的MFC的使用改为在共享DLL使用MFC
3、string/cstring的转化
1、string 转 CString
CString.format("%s", string.c_str());
2、char * 转 CString
CString.format("%s", char*);
3、char * 转 string
string s(char *);
4、string 转 char *
char *p = string.c_str();
5、CString 转 string
string s(CString.GetBuffer(CString.GetLength()));
6、CString 转 char *
charpoint=strtest.GetBuffer(strtest.GetLength());
不建议用(LPCTSTR)进行强制类型转化,这样strtest大小发生变化时会出现错误。
7、CString 转 char[100]
char a[100];
CString str("aaaaaa");
strncpy(a,(LPCTSTR)str,sizeof(a));
Keep it simple!