Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- #include <curl/curl.h>
- #include <gumbo.h>
- // Callback function for libcurl
- size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* output) {
- size_t totalSize = size * nmemb;
- output->append((char*)contents, totalSize);
- return totalSize;
- }
- // Function to fetch webpage content
- std::string fetchHTML(const std::string& url) {
- CURL* curl = curl_easy_init();
- std::string htmlContent;
- if (curl) {
- curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
- curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
- curl_easy_setopt(curl, CURLOPT_WRITEDATA, &htmlContent);
- curl_easy_perform(curl);
- curl_easy_cleanup(curl);
- }
- return htmlContent;
- }
- // Function to parse HTML and extract `<title>` tag
- void extractTitle(const std::string& html) {
- GumboOutput* output = gumbo_parse(html.c_str());
- GumboNode* root = output->root;
- if (root->type == GUMBO_NODE_ELEMENT) {
- GumboVector children = root->v.element.children;
- for (size_t i = 0; i < children.length; ++i) {
- GumboNode* child = (GumboNode*)children.data[i];
- if (child->type == GUMBO_NODE_ELEMENT && child->v.element.tag == GUMBO_TAG_TITLE) {
- std::cout << "Page Title: " << child->v.element.children.data[0] << std::endl;
- break;
- }
- }
- }
- gumbo_destroy_output(&kGumboDefaultOptions, output);
- }
- int main() {
- std::string url = "https://example.com";
- std::string html = fetchHTML(url);
- if (!html.empty()) {
- extractTitle(html);
- } else {
- std::cout << "Failed to fetch the webpage!" << std::endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment