htmltitle.cpp 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al.
  9. *
  10. * This software is licensed as described in the file COPYING, which
  11. * you should have received as part of this distribution. The terms
  12. * are also available at https://curl.haxx.se/docs/copyright.html.
  13. *
  14. * You may opt to use, copy, modify, merge, publish, distribute and/or sell
  15. * copies of the Software, and permit persons to whom the Software is
  16. * furnished to do so, under the terms of the COPYING file.
  17. *
  18. * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
  19. * KIND, either express or implied.
  20. *
  21. ***************************************************************************/
  22. /* <DESC>
  23. * Get a web page, extract the title with libxml.
  24. * </DESC>
  25. Written by Lars Nilsson
  26. GNU C++ compile command line suggestion (edit paths accordingly):
  27. g++ -Wall -I/opt/curl/include -I/opt/libxml/include/libxml2 htmltitle.cpp \
  28. -o htmltitle -L/opt/curl/lib -L/opt/libxml/lib -lcurl -lxml2
  29. */
  30. #include <stdio.h>
  31. #include <string.h>
  32. #include <stdlib.h>
  33. #include <string>
  34. #include <curl/curl.h>
  35. #include <libxml/HTMLparser.h>
  36. //
  37. // Case-insensitive string comparison
  38. //
  39. #ifdef _MSC_VER
  40. #define COMPARE(a, b) (!_stricmp((a), (b)))
  41. #else
  42. #define COMPARE(a, b) (!strcasecmp((a), (b)))
  43. #endif
  44. //
  45. // libxml callback context structure
  46. //
  47. struct Context
  48. {
  49. Context(): addTitle(false) { }
  50. bool addTitle;
  51. std::string title;
  52. };
  53. //
  54. // libcurl variables for error strings and returned data
  55. static char errorBuffer[CURL_ERROR_SIZE];
  56. static std::string buffer;
  57. //
  58. // libcurl write callback function
  59. //
  60. static int writer(char *data, size_t size, size_t nmemb,
  61. std::string *writerData)
  62. {
  63. if(writerData == NULL)
  64. return 0;
  65. writerData->append(data, size*nmemb);
  66. return size * nmemb;
  67. }
  68. //
  69. // libcurl connection initialization
  70. //
  71. static bool init(CURL *&conn, char *url)
  72. {
  73. CURLcode code;
  74. conn = curl_easy_init();
  75. if(conn == NULL) {
  76. fprintf(stderr, "Failed to create CURL connection\n");
  77. exit(EXIT_FAILURE);
  78. }
  79. code = curl_easy_setopt(conn, CURLOPT_ERRORBUFFER, errorBuffer);
  80. if(code != CURLE_OK) {
  81. fprintf(stderr, "Failed to set error buffer [%d]\n", code);
  82. return false;
  83. }
  84. code = curl_easy_setopt(conn, CURLOPT_URL, url);
  85. if(code != CURLE_OK) {
  86. fprintf(stderr, "Failed to set URL [%s]\n", errorBuffer);
  87. return false;
  88. }
  89. code = curl_easy_setopt(conn, CURLOPT_FOLLOWLOCATION, 1L);
  90. if(code != CURLE_OK) {
  91. fprintf(stderr, "Failed to set redirect option [%s]\n", errorBuffer);
  92. return false;
  93. }
  94. code = curl_easy_setopt(conn, CURLOPT_WRITEFUNCTION, writer);
  95. if(code != CURLE_OK) {
  96. fprintf(stderr, "Failed to set writer [%s]\n", errorBuffer);
  97. return false;
  98. }
  99. code = curl_easy_setopt(conn, CURLOPT_WRITEDATA, &buffer);
  100. if(code != CURLE_OK) {
  101. fprintf(stderr, "Failed to set write data [%s]\n", errorBuffer);
  102. return false;
  103. }
  104. return true;
  105. }
  106. //
  107. // libxml start element callback function
  108. //
  109. static void StartElement(void *voidContext,
  110. const xmlChar *name,
  111. const xmlChar **attributes)
  112. {
  113. Context *context = static_cast<Context *>(voidContext);
  114. if(COMPARE(reinterpret_cast<char *>(name), "TITLE")) {
  115. context->title = "";
  116. context->addTitle = true;
  117. }
  118. (void) attributes;
  119. }
  120. //
  121. // libxml end element callback function
  122. //
  123. static void EndElement(void *voidContext,
  124. const xmlChar *name)
  125. {
  126. Context *context = static_cast<Context *>(voidContext);
  127. if(COMPARE(reinterpret_cast<char *>(name), "TITLE"))
  128. context->addTitle = false;
  129. }
  130. //
  131. // Text handling helper function
  132. //
  133. static void handleCharacters(Context *context,
  134. const xmlChar *chars,
  135. int length)
  136. {
  137. if(context->addTitle)
  138. context->title.append(reinterpret_cast<char *>(chars), length);
  139. }
  140. //
  141. // libxml PCDATA callback function
  142. //
  143. static void Characters(void *voidContext,
  144. const xmlChar *chars,
  145. int length)
  146. {
  147. Context *context = static_cast<Context *>(voidContext);
  148. handleCharacters(context, chars, length);
  149. }
  150. //
  151. // libxml CDATA callback function
  152. //
  153. static void cdata(void *voidContext,
  154. const xmlChar *chars,
  155. int length)
  156. {
  157. Context *context = static_cast<Context *>(voidContext);
  158. handleCharacters(context, chars, length);
  159. }
  160. //
  161. // libxml SAX callback structure
  162. //
  163. static htmlSAXHandler saxHandler =
  164. {
  165. NULL,
  166. NULL,
  167. NULL,
  168. NULL,
  169. NULL,
  170. NULL,
  171. NULL,
  172. NULL,
  173. NULL,
  174. NULL,
  175. NULL,
  176. NULL,
  177. NULL,
  178. NULL,
  179. StartElement,
  180. EndElement,
  181. NULL,
  182. Characters,
  183. NULL,
  184. NULL,
  185. NULL,
  186. NULL,
  187. NULL,
  188. NULL,
  189. NULL,
  190. cdata,
  191. NULL
  192. };
  193. //
  194. // Parse given (assumed to be) HTML text and return the title
  195. //
  196. static void parseHtml(const std::string &html,
  197. std::string &title)
  198. {
  199. htmlParserCtxtPtr ctxt;
  200. Context context;
  201. ctxt = htmlCreatePushParserCtxt(&saxHandler, &context, "", 0, "",
  202. XML_CHAR_ENCODING_NONE);
  203. htmlParseChunk(ctxt, html.c_str(), html.size(), 0);
  204. htmlParseChunk(ctxt, "", 0, 1);
  205. htmlFreeParserCtxt(ctxt);
  206. title = context.title;
  207. }
  208. int main(int argc, char *argv[])
  209. {
  210. CURL *conn = NULL;
  211. CURLcode code;
  212. std::string title;
  213. // Ensure one argument is given
  214. if(argc != 2) {
  215. fprintf(stderr, "Usage: %s <url>\n", argv[0]);
  216. exit(EXIT_FAILURE);
  217. }
  218. curl_global_init(CURL_GLOBAL_DEFAULT);
  219. // Initialize CURL connection
  220. if(!init(conn, argv[1])) {
  221. fprintf(stderr, "Connection initializion failed\n");
  222. exit(EXIT_FAILURE);
  223. }
  224. // Retrieve content for the URL
  225. code = curl_easy_perform(conn);
  226. curl_easy_cleanup(conn);
  227. if(code != CURLE_OK) {
  228. fprintf(stderr, "Failed to get '%s' [%s]\n", argv[1], errorBuffer);
  229. exit(EXIT_FAILURE);
  230. }
  231. // Parse the (assumed) HTML code
  232. parseHtml(buffer, title);
  233. // Display the extracted title
  234. printf("Title: %s\n", title.c_str());
  235. return EXIT_SUCCESS;
  236. }