htmltitle.cpp 6.3 KB

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