您的位置:首页 > 编程语言 > C语言/C++

问答的形成-C++ 提取百度知道内容

2014-08-17 08:37 218 查看
因为项目 需要一份问答库进行测试

故提取百度知道内容

仅对如下链接格式的内容进行提取

zhidao.baidu.com/question/N.html

数字N的取值从0开始

bool PostHttpPage(const string& hostName, const string& pathName, const string& postData,int fileId)
{
using namespace std;
//fileId--;
//创建一个会话对象来初始化WINNET库
CInternetSession session("my session ");
//连接对象
CHttpConnection* pConnect=NULL;

try
{
INTERNET_PORT nPort = 80;
DWORD dwRet = 0;
//建立连接,从session中获取,不用自己创建
pConnect = session.GetHttpConnection(hostName.c_str(), nPort);

CHttpFile* pFile = pConnect->OpenRequest(CHttpConnection::HTTP_VERB_POST, pathName.c_str());

CString strHeaders = "Content-Type: application/x-www-form-urlencoded"; // 请求头

//开始发送请求

pFile->SendRequest(strHeaders,(LPVOID)postData.c_str(),postData.size());
pFile->QueryInfoStatusCode(dwRet);

if (dwRet == HTTP_STATUS_OK)
{
CString result, newline;
int flag=0;
//
string key;
string ques;
string ans;
//新的请求才会置零
int tFlag=0;

int start;
int end;

while(pFile->ReadString(newline))
{//循环读取每行内容
//result += newline+"\r\n";
//std::cout<<newline<<std::endl;
//Sleep(300);
//////////////////////////////////////////////////////////////////////////
//在这里对提取的信息进行处理

//某些已经被删或者不存在啥的,就跳过
int i=newline.Find("百度知道 - 信息提示");
if(string::npos!=i)
break;

//可能问题中包含图片,也可以直接忽略了
/*int j=newline.Find("img class=\"word-replace\"");
i=newline.Find("img class=\"ikqb_img\"");
i=i<j?i:j;*/
i=newline.Find("img class=");
if(string::npos!=i)
break;

//找关键字
i=newline.Find("<meta name=\"keywords\" content=\"");

if (string::npos!=i)
{
//string ss=newline.GetBuffer();
start=i+strlen("<meta name=\"keywords\" content=\"");
end=newline.Find(">");
end-=2;
key=newline.Mid(start,end-start);

//鉴于检索引擎编码上存在问题,就去掉没有关键字的吧
if(!strcmp(key.c_str(),""))
break;

tFlag++;
continue;
}
//找具体问题内容
i=newline.Find("<span class=\"ask-title\">");
if(string::npos!=i)
{
start=i+strlen("<span class=\"ask-title\">");;
end=newline.Find("</span>");

ques=newline.Mid(start,end-start);
tFlag++;
continue;

}

//找答案
//先只找一个
/*i=newline.Find("recommend-content");
int j=newline.Find("answer-content");
i=i>j?i:j;*/
//i=newline.Find("answer-content");
i=newline.Find("class=\"answer-text mb-10\">");
if (string::npos!=i)
{
newline.Replace("<br />","");
newline.Replace("</ br>","");
start=i+strlen("class=\"answer-text mb-10\">");
end=newline.Find("</pre>");
ans=newline.Mid(start,end-start);
tFlag++;
break;
}

}
//tFlag等于3的时候才认为信息完全
if(tFlag==3)
{
cout<<"key:"<<key<<endl;
cout<<"ques:"<<ques<<endl;
cout<<"ans:"<<ans<<endl;
AddChildren(key,ques,ans,fileId);//这个函数是向文件中增加子节点的,libxml2实现

}

//std::cout<<result<<std::endl;//显示返回内容
}
else
{
return false;
}
delete pFile;
if(pConnect!=NULL)
{
pConnect->Close();
delete pConnect;
}

}
catch (CInternetException* pEx)
{
//catch errors from WinInet
TCHAR pszError[200];
pEx->GetErrorMessage(pszError, 200);

std::cout<<pszError<<std::endl;//显示异常信息
return false;
}
session.Close();

return true;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: