有关Html Parser的使用范例, URL解析器

来源:互联网 发布:郑州大学网络教育官网 编辑:程序博客网 时间:2024/04/29 05:00
  1. 摘自陈华的BLOG, 如果你不知道陈华是谁,请访问www.kooxoo.com^_^
  2. /*
  3. file: urlparser.h
  4. desc: parse a html page, get each url and its link text
  5. author: chen hua 
  6. create: 2005-03-16
  7. */
  8. #ifndef _URL_PARSER_H_
  9. #define _URL_PARSER_H_ 
  10. #include "basehtmlparser.h"
  11. #include <map>
  12. #include <string>
  13. using namespace std; 
  14. class CURLParser: public CBaseHtmlParser
  15. {
  16. public:
  17.     CURLParser(){m_bInTagA=false;}
  18.     bool Parse(const string& URL,const string& Content);
  19. public
  20.     map<string,string> m_URL2Text;
  21. private:
  22.     bool m_bInTagA;
  23.     string m_strCurURL;
  24.     void OnStartTag(const SZ_STRING & strTagName,vector< pair<SZ_STRING,SZ_STRING> > Attribs);
  25.     void OnEndTag(const SZ_STRING & strTagName);
  26.     void OnData(const SZ_STRING & strData);
  27. }; 
  28. #endif 
  29. #include "urlparser.h" 
  30. #ifndef WIN32
  31. #define strnicmp strncasecmp
  32. #endif 
  33. bool CURLParser::Parse(const string& URL,const string& Content)
  34. {
  35.     m_URL2Text.clear();
  36.     return CBaseHtmlParser::Parse(URL,Content);
  37. void CURLParser::OnStartTag(const SZ_STRING & strTagName,vector< pair<SZ_STRING,SZ_STRING> > Attribs)
  38. {
  39.     if((strTagName.cbData==1)&&(strnicmp(strTagName.pbData,"A",strTagName.cbData)==0))
  40.     {
  41.         m_bInTagA=true;
  42.         m_strCurURL.clear();
  43.         for(size_t i=0;i<Attribs.size();i++)
  44.         {
  45.             SZ_STRING x=Attribs[i].first;
  46.             if((Attribs[i].first.cbData==4)&&(strnicmp(Attribs[i].first.pbData,"href",Attribs[i].first.cbData)==0))
  47.             {
  48.                 m_strCurURL=string(Attribs[i].second.pbData,Attribs[i].second.cbData);
  49.                 Relativity2AbsoluteURL(m_strCurURL);
  50.                 break;
  51.             }
  52.         }
  53.     }
  54. void CURLParser::OnEndTag(const SZ_STRING & strTagName)
  55. {
  56.     if((strTagName.cbData==1)&&(strnicmp(strTagName.pbData,"A",strTagName.cbData)==0))
  57.     {
  58.         m_bInTagA=false;
  59.     }
  60.     if((strTagName.cbData==2)&&(strnicmp(strTagName.pbData,"td",strTagName.cbData)==0))
  61.     {
  62.         m_bInTagA=false;
  63.     }
  64. void CURLParser::OnData(const SZ_STRING & strData)
  65. {
  66.     if(m_bInTagA)
  67.     {
  68.         if(!m_strCurURL.empty())
  69.             m_URL2Text[m_strCurURL]=m_URL2Text[m_strCurURL]+string(strData.pbData,strData.cbData);
  70.     }
  71. }