htmltitle.cpp 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 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 _WIN32
  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 size_t 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, const 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<const 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<const 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<const char *>(chars),
  141. (unsigned long)length);
  142. }
  143. //
  144. // libxml PCDATA callback function
  145. //
  146. static void Characters(void *voidContext,
  147. const xmlChar *chars,
  148. int length)
  149. {
  150. Context *context = static_cast<Context *>(voidContext);
  151. handleCharacters(context, chars, length);
  152. }
  153. //
  154. // libxml CDATA callback function
  155. //
  156. static void cdata(void *voidContext,
  157. const xmlChar *chars,
  158. int length)
  159. {
  160. Context *context = static_cast<Context *>(voidContext);
  161. handleCharacters(context, chars, length);
  162. }
  163. //
  164. // libxml SAX callback structure
  165. //
  166. static htmlSAXHandler saxHandler =
  167. {
  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. NULL,
  182. StartElement,
  183. EndElement,
  184. NULL,
  185. Characters,
  186. NULL,
  187. NULL,
  188. NULL,
  189. NULL,
  190. NULL,
  191. NULL,
  192. NULL,
  193. cdata,
  194. NULL,
  195. 0,
  196. 0,
  197. 0,
  198. 0,
  199. NULL
  200. };
  201. //
  202. // Parse given (assumed to be) HTML text and return the title
  203. //
  204. static void parseHtml(const std::string &html,
  205. std::string &title)
  206. {
  207. htmlParserCtxtPtr ctxt;
  208. Context context;
  209. ctxt = htmlCreatePushParserCtxt(&saxHandler, &context, "", 0, "",
  210. XML_CHAR_ENCODING_NONE);
  211. htmlParseChunk(ctxt, html.c_str(), (int)html.size(), 0);
  212. htmlParseChunk(ctxt, "", 0, 1);
  213. htmlFreeParserCtxt(ctxt);
  214. title = context.title;
  215. }
  216. int main(int argc, char *argv[])
  217. {
  218. CURL *conn = NULL;
  219. CURLcode code;
  220. std::string title;
  221. // Ensure one argument is given
  222. if(argc != 2) {
  223. fprintf(stderr, "Usage: %s <url>\n", argv[0]);
  224. exit(EXIT_FAILURE);
  225. }
  226. curl_global_init(CURL_GLOBAL_DEFAULT);
  227. // Initialize CURL connection
  228. if(!init(conn, argv[1])) {
  229. fprintf(stderr, "Connection initialization failed\n");
  230. exit(EXIT_FAILURE);
  231. }
  232. // Retrieve content for the URL
  233. code = curl_easy_perform(conn);
  234. curl_easy_cleanup(conn);
  235. if(code != CURLE_OK) {
  236. fprintf(stderr, "Failed to get '%s' [%s]\n", argv[1], errorBuffer);
  237. exit(EXIT_FAILURE);
  238. }
  239. // Parse the (assumed) HTML code
  240. parseHtml(buffer, title);
  241. // Display the extracted title
  242. printf("Title: %s\n", title.c_str());
  243. return EXIT_SUCCESS;
  244. }