Форум программистов, компьютерный форум, киберфорум
Boost C++
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.62/47: Рейтинг темы: голосов - 47, средняя оценка - 4.62
0 / 0 / 0
Регистрация: 14.10.2018
Сообщений: 32

Скачать html страницу (boost.beast)

03.01.2019, 17:42. Показов 9511. Ответов 11
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Всем доброе время суток, дали задачу реализовать crawler,скачать html страницу необходимо с помощью boost.beast к сожалению потратив очень много времени разобраться в документации этого чуда я не смог, обьясните пожалуйста как скачать html страницу с помощью boost beast
0
Лучшие ответы (1)
cpp_developer
Эксперт
20123 / 5690 / 1417
Регистрация: 09.04.2010
Сообщений: 22,546
Блог
03.01.2019, 17:42
Ответы с готовыми решениями:

Boost::regex, как правильно парсить HTML
Всем доброго времени суток. В общем проблема возникла с получением значений из html кода. Записываю в char текст такого содержания: ...

boost/regex Поиск ссылок в html-файле
Нашел вот такой код: #include <iostream> #include <string> #include <boost/regex.hpp> #include <fstream> using namespace...

Парсинг html кода с использованием регулярных выражений (в частности boost.regex)
Вечер добрый, уважаемые форумчане! В общем то тема избитая, читал я по ней много, но из темы в тему - только какие то второстепенные...

11
 Аватар для igorrr37
2895 / 2042 / 992
Регистрация: 21.12.2010
Сообщений: 3,791
Записей в блоге: 9
03.01.2019, 18:34
Лучший ответ Сообщение было отмечено Peoples как решение

Решение

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#include "C:/boost_1_68_0_VS2017/libs/beast/example/common/root_certificates.hpp" // прописать свой путь
#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <boost/beast/version.hpp>
#include <boost/asio/connect.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/ssl/error.hpp>
#include <boost/asio/ssl/stream.hpp>
#include <cstdlib>
#include <iostream>
#include <string>
#include <fstream>
 
using tcp = boost::asio::ip::tcp;       // from <boost/asio/ip/tcp.hpp>
namespace ssl = boost::asio::ssl;       // from <boost/asio/ssl.hpp>
namespace http = boost::beast::http;    // from <boost/beast/http.hpp>
 
// Performs an HTTP GET and prints the response
int main(int argc, char** argv)
{
    try
    {
        "Usage: http-client-sync-ssl <host> <port> <target> [<HTTP version: 1.0 or 1.1(default)>]\n" 
        "Example:\n" 
        "    http-client-sync-ssl www.example.com 443 /\n" 
        "    http-client-sync-ssl www.example.com 443 / 1.0\n";
 
        // адрес страницы для скачивания: https://www.boost.org/doc/libs/1_69_0/libs/beast/example/http/client/sync-ssl/http_client_sync_ssl.cpp
 
        auto const host = "www.boost.org"; 
        auto const port = "443"; // https - 443, http - 80
        auto const target = "/doc/libs/1_69_0/libs/beast/example/http/client/sync-ssl/http_client_sync_ssl.cpp"; // 
        int version = argc == 5 && !std::strcmp("1.0", argv[4]) ? 10 : 11;
 
        // The io_context is required for all I/O
        boost::asio::io_context ioc;
 
        // The SSL context is required, and holds certificates
        ssl::context ctx{ ssl::context::sslv23_client };
 
        // This holds the root certificate used for verification
        load_root_certificates(ctx);
 
        // Verify the remote server's certificate
        //ctx.set_verify_mode(ssl::verify_peer);
 
        // These objects perform our I/O
        tcp::resolver resolver{ ioc };
        ssl::stream<tcp::socket> stream{ ioc, ctx };
 
        // Set SNI Hostname (many hosts need this to handshake successfully)
        if (!SSL_set_tlsext_host_name(stream.native_handle(), host))
        {
            boost::system::error_code ec{ static_cast<int>(::ERR_get_error()), boost::asio::error::get_ssl_category() };
            throw boost::system::system_error{ ec };
        }
 
        // Look up the domain name
        auto const results = resolver.resolve(host, port);
 
        // Make the connection on the IP address we get from a lookup
        boost::asio::connect(stream.next_layer(), results.begin(), results.end());
 
        // Perform the SSL handshake
        stream.handshake(ssl::stream_base::client);
 
        // Set up an HTTP GET request message
        http::request<http::string_body> req{ http::verb::get, target, version };
        req.set(http::field::host, host);
        req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING);
 
        // Send the HTTP request to the remote host
        http::write(stream, req);
 
        // This buffer is used for reading and must be persisted
        boost::beast::flat_buffer buffer;
 
        // Declare a container to hold the response
        http::response<http::dynamic_body> res;
 
        // Receive the HTTP response
        http::read(stream, buffer, res);
 
        // Write the message to out
        std::ofstream ofs{"out.txt"}; // запись html-страницы в файл
        ofs << res;
        ofs.close();
 
        // Gracefully close the stream
        boost::system::error_code ec;
        stream.shutdown(ec);
        if (ec == boost::asio::error::eof)
        {
            // Rationale:
            // http://stackoverflow.com/questions/25587403/boost-asio-ssl-async-shutdown-always-finishes-with-an-error
            ec.assign(0, ec.category());
        }
        if (ec)
            throw boost::system::system_error{ ec };
 
        // If we get here then the connection is closed gracefully
    }
    catch (std::exception const& e)
    {
        std::cerr << "Error: " << e.what() << std::endl;
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}
1
0 / 0 / 0
Регистрация: 14.10.2018
Сообщений: 32
03.01.2019, 18:47  [ТС]
Ты серьезно? спасибо огромное,этот пример я и сам нашел, только я попросил обьяснить как это сделать и как это работает, к тому же я уверен что можно это сделать немного проще, мне так кажется во всяком случае
0
 Аватар для igorrr37
2895 / 2042 / 992
Регистрация: 21.12.2010
Сообщений: 3,791
Записей в блоге: 9
04.01.2019, 11:01
Это не пример а код для скачивания https-страницы сайта. Кажется, вопрос был именно в этом. А вот насчёт "можно это сделать немного проще" что то сомнительно.
Да, и OpenSSL должен быть установлен сборка OpenSSL для MSVS2017
0
0 / 0 / 0
Регистрация: 14.10.2018
Сообщений: 32
04.01.2019, 19:33  [ТС]
да ,извините , вы правы , собрал я это без проблем особы , все работает, потихоньку разбираюсь, у меня к вам еще один вопрос, скажите пожалуйста если задача стоит рекурсивно обойти все ссылки на страницы это тоже нужно использовать boost.beast или что-то другое? вообще с задании нужно использовать boost.beast and gumbo parser ,вот пытаюсь разобраться что для чего
0
 Аватар для igorrr37
2895 / 2042 / 992
Регистрация: 21.12.2010
Сообщений: 3,791
Записей в блоге: 9
05.01.2019, 16:28
Загружает исходную страницу и выводит в консоль все найденные на ней ссылки. Работает пока только с https-страницами. Парсер - gumbo.
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
#include "C:/boost_1_68_0_VS2017/libs/beast/example/common/root_certificates.hpp" // прописать свой путь
#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <boost/beast/version.hpp>
#include <boost/asio/connect.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/ssl/error.hpp>
#include <boost/asio/ssl/stream.hpp>
#include <cstdlib>
#include <iostream>
#include <string>
#include <fstream>
#include <regex>
#include <queue>
#include <vector>
#include "gumbo.h"
 
using tcp = boost::asio::ip::tcp;       
namespace ssl = boost::asio::ssl;       
namespace http = boost::beast::http;    
 
void findLinks(std::string const& sBody, std::vector<std::string>& vLinks)
{
    GumboOutput* output = gumbo_parse(sBody.c_str());
 
    std::queue<GumboNode*> qn;
    qn.push(output->root);
 
    while (!qn.empty())
    {
        GumboNode* node = qn.front();
        qn.pop();
 
        if (GUMBO_NODE_ELEMENT == node->type)
        {
            GumboAttribute* href = nullptr;
            if (node->v.element.tag == GUMBO_TAG_A && (href = gumbo_get_attribute(&node->v.element.attributes, "href")))
            {
                vLinks.push_back(href->value);
            }
 
            GumboVector* children = &node->v.element.children;
            for (unsigned int i = 0; i < children->length; ++i)
            {
                qn.push(static_cast<GumboNode*>(children->data[i]));
            }
        }
    }
 
    gumbo_destroy_output(&kGumboDefaultOptions, output);
}
 
// протестировано в MSVS2017
int main()
{
    system("chcp 1251");
    try
    {
        std::string sUri{ "https://mail.ru" }; // адрес исходной страницы
        std::regex rUri{ "^(?:(https?)://)?([^/]+)(/.*)?" };
 
        std::smatch mr;
        if (std::regex_match(sUri, mr, rUri))
        {
            for (auto const& sm : mr)
            {
                //std::cout << sm << std::endl;
            }
        }
        else
        {
            std::cerr << "std::regex_match failed: " + sUri << "\n\n";
        }
        if (mr[1].str() != "https") // работает пока только с https
        {
            std::cerr << "mr[1].str() != \"https\"" << "\n\n";
        }
 
        std::string const host = mr[2];
        std::string const port = "443"; // https - 443, http - 80
        std::string const target = (mr[3].length() == 0 ? "/" : mr[3].str());
        int version = 11; // или 10 для http 1.0
 
        boost::asio::io_context ioc;
        ssl::context ctx{ ssl::context::sslv23_client };
        load_root_certificates(ctx);
        tcp::resolver resolver{ ioc };
        ssl::stream<tcp::socket> stream{ ioc, ctx };
        if (!SSL_set_tlsext_host_name(stream.native_handle(), host.c_str()))
        {
            boost::system::error_code ec{ static_cast<int>(::ERR_get_error()), boost::asio::error::get_ssl_category() };
            throw boost::system::system_error{ ec };
        }
        auto const results = resolver.resolve(host, port);
        boost::asio::connect(stream.next_layer(), results.begin(), results.end());
        stream.handshake(ssl::stream_base::client);
        http::request<http::string_body> req{ http::verb::get, target, version };
        req.set(http::field::host, host);
        req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING);
        http::write(stream, req);
        boost::beast::flat_buffer buffer;
        http::response<http::dynamic_body> res;
        http::read(stream, buffer, res);
        std::string sBody = boost::beast::buffers_to_string(res.body().data());
 
        std::ofstream ofs{ "out.txt" }; // запись html-страницы в файл
        ofs << sBody;
        ofs.close();
 
        std::vector<std::string> vLinks;
        findLinks(sBody, vLinks);
        for (auto const& val : vLinks)
        {
            std::cout << val << std::endl; // вывод найденных ссылок
        }
 
        // Gracefully close the stream
        boost::system::error_code ec;
        stream.shutdown(ec);
        if (ec == boost::asio::error::eof)
        {
            // Rationale:
            // http://stackoverflow.com/questions/25587403/boost-asio-ssl-async-shutdown-always-finishes-with-an-error
            ec.assign(0, ec.category());
        }
        if (ec)
            throw boost::system::system_error{ ec };
    }
    catch (std::exception const& e)
    {
        std::cerr << "Error: " << e.what() << std::endl;
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}
0
0 / 0 / 0
Регистрация: 14.10.2018
Сообщений: 32
05.01.2019, 18:14  [ТС]
igorrr37, спасибо большое)

Добавлено через 45 минут
igorrr37, я кстати правильно понимаю что это ассинхронный вариант? начал разбираться в этом более глубоко и как оказалось io_context класс для работы с асинхронными соединениями
0
 Аватар для igorrr37
2895 / 2042 / 992
Регистрация: 21.12.2010
Сообщений: 3,791
Записей в блоге: 9
05.01.2019, 18:34
Это синхронный. Для асинхронного надо юзать ф-ции с приставкой async_. Ещё возможен вариант на корутинах.

Добавлено через 2 минуты
Вот асинхронный
0
 Аватар для igorrr37
2895 / 2042 / 992
Регистрация: 21.12.2010
Сообщений: 3,791
Записей в блоге: 9
06.01.2019, 15:30
Добавил глубину обхода и загрузку http-страниц. Работает только с абсолютными ссылками
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
#include "C:/boost_1_68_0_VS2017/libs/beast/example/common/root_certificates.hpp" // прописать свой путь
#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <boost/beast/version.hpp>
#include <boost/asio/connect.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/ssl/error.hpp>
#include <boost/asio/ssl/stream.hpp>
#include <boost/asio/thread_pool.hpp>
#include <cstdlib>
#include <iostream>
#include <string>
#include <fstream>
#include <regex>
#include <queue>
#include <vector>
#include <thread>
#include <mutex>
#include <functional>
#include <iomanip>
#include "gumbo.h"
 
using tcp = boost::asio::ip::tcp;
namespace ssl = boost::asio::ssl;
namespace http = boost::beast::http;
 
class loader
{
public:
    loader(boost::asio::io_context& ioc_) : ioc(ioc_) {}
 
    std::vector<std::string> findLinks(std::string const& sBody)
    {
        std::vector<std::string> vLinks;
 
        GumboOutput* output = gumbo_parse(sBody.c_str());
 
        std::queue<GumboNode*> qn;
        qn.push(output->root);
 
        while (!qn.empty())
        {
            GumboNode* node = qn.front();
            qn.pop();
 
            if (GUMBO_NODE_ELEMENT == node->type)
            {
                GumboAttribute* href = nullptr;
                if (node->v.element.tag == GUMBO_TAG_A && (href = gumbo_get_attribute(&node->v.element.attributes, "href")))
                {
                    vLinks.push_back(href->value);
                }
 
                GumboVector* children = &node->v.element.children;
                for (unsigned int i = 0; i < children->length; ++i)
                {
                    qn.push(static_cast<GumboNode*>(children->data[i]));
                }
            }
        }
 
        gumbo_destroy_output(&kGumboDefaultOptions, output);
 
        return vLinks;
    }
 
    void load(std::string const& sUri, std::vector<std::string>& vres)
    {
        std::smatch mr;
        if (std::regex_match(sUri, mr, rUri))
        {
            for (auto const& sm : mr)
            {
                {
                    //std::lock_guard<std::mutex> lg{ mtx };
                    //std::cout << sm << std::endl;
                }
            }
 
            if (mr[1].str() == "http")
            {
                vres = loadHttp(mr);
            }
            else
            {
                vres = loadHttps(mr);
            }
        }
        else
        {
            {
                std::lock_guard<std::mutex> lg{ mtx };
                std::cerr << "load() std::regex_match() failed: " + sUri << "\n\n";
            }
        }
    }
 
    std::vector<std::string> loadHttp(std::smatch const& mr)
    {
        std::vector<std::string> vLinks;
        try {
            std::string const target = (mr[3].length() == 0 ? "/" : mr[3].str());
            int version = 11; // или 10 для http 1.0
 
            tcp::socket socket{ ioc };
            tcp::resolver resolver{ ioc };
            auto const results = resolver.resolve(mr[2], "80");
            boost::asio::connect(socket, results.begin(), results.end());
            http::request<http::string_body> req{ http::verb::get, target, version };
            req.set(http::field::host, mr[2]);
            req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING);
            http::write(socket, req);
            boost::beast::flat_buffer buffer;
            http::response<http::dynamic_body> res;
            http::read(socket, buffer, res);
 
            std::string sBody = boost::beast::buffers_to_string(res.body().data());
            //std::ofstream ofs{ "out.txt" }; // запись html-страницы в файл
            //ofs << sBody;
            //ofs.close();
 
            vLinks = findLinks(sBody);
 
            boost::system::error_code ec;
            socket.shutdown(tcp::socket::shutdown_both, ec);
            if (ec && ec != boost::system::errc::not_connected)
                throw boost::system::system_error{ ec };
 
        }
        catch (std::exception const& e)
        {
            {
                std::lock_guard<std::mutex> lg{ mtx };
                std::cerr << "loadHttp(): " << e.what() << std::endl;
            }
        }
        return vLinks;
    }
 
    std::vector<std::string> loadHttps(std::smatch const& mr)
    {
        std::vector<std::string> vLinks;
        try {
 
            std::string const host = mr[2];
            std::string const target = (mr[3].length() == 0 ? "/" : mr[3].str());
            int version = 11; // или 10 для http 1.0
 
            ssl::context ctx{ ssl::context::sslv23_client };
            load_root_certificates(ctx);
            ssl::stream<tcp::socket> stream{ ioc, ctx };
            if (!SSL_set_tlsext_host_name(stream.native_handle(), host.c_str()))
            {
                boost::system::error_code ec{ static_cast<int>(::ERR_get_error()), boost::asio::error::get_ssl_category() };
                throw boost::system::system_error{ ec };
            }
            tcp::resolver resolver{ ioc };
            auto const results = resolver.resolve(host, "443");
            boost::asio::connect(stream.next_layer(), results.begin(), results.end());
            stream.handshake(ssl::stream_base::client);
            http::request<http::string_body> req{ http::verb::get, target, version };
            req.set(http::field::host, host);
            req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING);
            http::write(stream, req);
            boost::beast::flat_buffer buffer;
            http::response<http::dynamic_body> res;
            http::read(stream, buffer, res);
 
            std::string sBody = boost::beast::buffers_to_string(res.body().data());
            //std::ofstream ofs{ "out.txt" }; // запись html-страницы в файл
            //ofs << sBody;
            //ofs.close();
 
            vLinks = findLinks(sBody);
 
            boost::system::error_code ec;
            stream.shutdown(ec);
            if (ec == boost::asio::error::eof)
            {
                // Rationale:
                // http://stackoverflow.com/questions/25587403/boost-asio-ssl-async-shutdown-always-finishes-with-an-error
                ec.assign(0, ec.category());
            }
            if (ec)
                throw boost::system::system_error{ ec };
 
        }
        catch (std::exception const& e)
        {
            {
                std::lock_guard<std::mutex> lg{ mtx };
                std::cerr << "loadHttps(): " << e.what() << std::endl;
            }
        }
        return vLinks;
    }
 
    loader(loader const&) = delete;
    loader& operator=(loader const&) = delete;
 
private:
    std::regex rUri{ "^(?:(https?)://)([^/]+)(/.*)?" };
    std::mutex mtx;
    boost::asio::io_context& ioc;
};
 
// протестировано в MSVS2017
int main()
{
    system("chcp 1251");
 
    boost::asio::io_context ioc;
    loader ldr{ ioc };
 
    std::vector<std::string> vUri
    {
        "https://www.boost.org/doc/libs/1_69_0/libs/beast/example/http/client/sync-ssl/http_client_sync_ssl.cpp" // начальная ссылка
    };
 
    std::vector<std::vector<std::string>> vres;
 
    int dpth = 2; // глубина обхода
    while (dpth--)
    {
        vres.clear();
        vres.reserve(vUri.size()); // чтобы не переаллоцировался
 
        // вектор vUri обрабатывается пулом из 4 потоков
        boost::asio::thread_pool tpool{ 4 };
        for (auto const& sUri : vUri)
        {
            vres.emplace_back();
            boost::asio::post(tpool, std::bind(&loader::load, &ldr, std::cref(sUri), std::ref(vres.back())));
        }
        tpool.join();
 
        // вывод результата
        std::cout << "\nСтраниц: " << vUri.size() << " **************************************************************************************************\n\n";
        for(int i = 0; i < vres.size(); ++i)
        {
            std::cout << "Ссылок: " << std::setw(6) << std::left << vres.at(i).size() << vUri.at(i) << "\n\n";
            for (auto const& str : vres.at(i))
            {
                //std::cout << str << std::endl; // вывод найденных ссылок
            }
        }
 
        // перед заходом на следующую итерацию перекидываем все найденные ссылки из vres в vUri 
        vUri.clear();
        for (auto const& vct : vres)
        {
            vUri.insert(vUri.end(), vct.begin(), vct.end());
        }
    }
 
}
0
0 / 0 / 0
Регистрация: 14.10.2018
Сообщений: 32
07.01.2019, 16:02  [ТС]
igorrr37, Спасибо.я немного не понгимаю некоторых моментов,зачем в начале вектор строк для 1 ссылки? разве непроще создать просто строку?
0
0 / 0 / 0
Регистрация: 14.10.2018
Сообщений: 32
08.01.2019, 18:31  [ТС]
igorrr37, скажите,при рекурсивном обходе ссылок с глубиной скажем 2-3 или больше это нормально что одна и таже ссылка встречается несколько раз? я полагаю что в принципе так и должно быть ведь со вспомогательных страниц или каких-то других ресурсов может вести ссылка на главную страницу,да и в целом одна и та жа ссылка может встречаться на нескольких разных ссылках,у меня вопрос,как этого избежать?
0
 Аватар для igorrr37
2895 / 2042 / 992
Регистрация: 21.12.2010
Сообщений: 3,791
Записей в блоге: 9
09.01.2019, 15:44
Добавил исправление некоторых относительных ссылок в абсолютные, удаление повторяющихся ссылок и учёт тега <base>
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
#include "C:/boost_1_68_0_VS2017/libs/beast/example/common/root_certificates.hpp" // прописать свой путь
#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <boost/beast/version.hpp>
#include <boost/asio/connect.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/ssl/error.hpp>
#include <boost/asio/ssl/stream.hpp>
#include <boost/asio/thread_pool.hpp>
#include <cstdlib>
#include <iostream>
#include <string>
#include <fstream>
#include <regex>
#include <queue>
#include <vector>
#include <thread>
#include <mutex>
#include <functional>
#include <iomanip>
#include <unordered_set>
#include "gumbo.h"
 
using tcp = boost::asio::ip::tcp;
namespace ssl = boost::asio::ssl;
namespace http = boost::beast::http;
 
class loader
{
public:
    loader(boost::asio::io_context& ioc_) : ioc(ioc_) {}
 
    std::vector<std::string> findLinks(std::string const& sBody)
    {
        std::vector<std::string> vLinks;
 
        GumboAttribute* hrefBase = nullptr;
        GumboOutput* output = gumbo_parse(sBody.c_str());
 
        std::queue<GumboNode*> qn;
        qn.push(output->root);
 
        while (!qn.empty())
        {
            GumboNode* node = qn.front();
            qn.pop();
            if (GUMBO_NODE_ELEMENT == node->type)
            {
                GumboAttribute* href = nullptr;
                if (node->v.element.tag == GUMBO_TAG_A && (href = gumbo_get_attribute(&node->v.element.attributes, "href")))
                {
                    std::string sLnk{ href->value };
                    if (!sLnk.empty())
                    {
                        vLinks.emplace_back(href->value);
                    }
                }
                else if (node->v.element.tag == GUMBO_TAG_BASE && (hrefBase = gumbo_get_attribute(&node->v.element.attributes, "href")))
                {
                }
                GumboVector* children = &node->v.element.children;
                for (unsigned int i = 0; i < children->length; ++i)
                {
                    qn.push(static_cast<GumboNode*>(children->data[i]));
                }
            }
        }
 
        if (hrefBase) // с учётом тега <base>
        {
            std::string sBase = hrefBase->value;
            {
                //std::lock_guard<std::mutex> lg{ mtx };
                //std::cout << "<base> found: " << sBase << "\n\n";
            }
            if (sBase.back() == '/')
            {
                sBase.pop_back();
            }
            for (auto& sLnk : vLinks)
            {
                if (std::regex_match(sLnk, std::regex{ "(?:[^/]+/)+[^/]+" }) || std::regex_match(sLnk, std::regex{ "[^/#?]+" })) // относительно дочерней или текущей директории
                {
                    sLnk = sBase + '/' + sLnk;
                }
                else if (sLnk.find("../") == 0) // относительно родительской директории
                {
                    int ind = std::string::npos;
                    int cnt = (sLnk.rfind("../") + 3) / 3;
                    for (int i = 0; i < cnt + 1; ++i)
                    {
                        ind = sBase.rfind('/', ind - 1);
                    }
                    sLnk = std::string{ sBase.begin(), sBase.begin() + ind + 1 } +std::string{ sLnk.begin() + cnt * 3, sLnk.end() };
                }
                sLnk;
            }
        }
 
        gumbo_destroy_output(&kGumboDefaultOptions, output);
        return vLinks;
    }
 
    void load(std::string const& sUri, std::vector<std::string>& vres)
    {
        std::smatch mr;
        if (std::regex_match(sUri, mr, rUri))
        {
            if (mr[1].str() == "http")
            {
                vres = loadHttp(mr);
            }
            else
            {
                vres = loadHttps(mr);
            }
        }
        else
        {
            {
                std::lock_guard<std::mutex> lg{ mtx };
                std::cerr << "load() std::regex_match() failed: " + sUri << "\n\n";
            }
        }
    }
 
    std::vector<std::string> loadHttp(std::smatch const& mr)
    {
        std::vector<std::string> vLinks;
        try {
            std::string const target = (mr[3].length() == 0 ? "/" : mr[3].str());
            int version = 11; // или 10 для http 1.0
 
            tcp::socket socket{ ioc };
            tcp::resolver resolver{ ioc };
            auto const results = resolver.resolve(mr[2], "80");
            boost::asio::connect(socket, results.begin(), results.end());
            http::request<http::string_body> req{ http::verb::get, target, version };
            req.set(http::field::host, mr[2]);
            req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING);
            http::write(socket, req);
            boost::beast::flat_buffer buffer;
            http::response<http::dynamic_body> res;
            http::read(socket, buffer, res);
 
            std::string sBody = boost::beast::buffers_to_string(res.body().data());
            vLinks = findLinks(sBody);
 
            boost::system::error_code ec;
            socket.shutdown(tcp::socket::shutdown_both, ec);
            if (ec && ec != boost::system::errc::not_connected)
                throw boost::system::system_error{ ec };
 
        }
        catch (std::exception const& e)
        {
            {
                std::lock_guard<std::mutex> lg{ mtx };
                std::cerr << "loadHttp(): " << e.what() << std::endl;
            }
        }
        return vLinks;
    }
 
    std::vector<std::string> loadHttps(std::smatch const& mr)
    {
        std::vector<std::string> vLinks;
        try {
 
            std::string const host = mr[2];
            std::string const target = (mr[3].length() == 0 ? "/" : mr[3].str());
            int version = 11; // или 10 для http 1.0
 
            ssl::context ctx{ ssl::context::sslv23_client };
            load_root_certificates(ctx);
            ssl::stream<tcp::socket> stream{ ioc, ctx };
            if (!SSL_set_tlsext_host_name(stream.native_handle(), host.c_str()))
            {
                boost::system::error_code ec{ static_cast<int>(::ERR_get_error()), boost::asio::error::get_ssl_category() };
                throw boost::system::system_error{ ec };
            }
            tcp::resolver resolver{ ioc };
            auto const results = resolver.resolve(host, "443");
            boost::asio::connect(stream.next_layer(), results.begin(), results.end());
            stream.handshake(ssl::stream_base::client);
            http::request<http::string_body> req{ http::verb::get, target, version };
            req.set(http::field::host, host);
            req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING);
            http::write(stream, req);
            boost::beast::flat_buffer buffer;
            http::response<http::dynamic_body> res;
            http::read(stream, buffer, res);
 
            std::string sBody = boost::beast::buffers_to_string(res.body().data());
            vLinks = findLinks(sBody);
 
            boost::system::error_code ec;
            stream.shutdown(ec);
            if (ec == boost::asio::error::eof)
            {
                // Rationale:
                // http://stackoverflow.com/questions/25587403/boost-asio-ssl-async-shutdown-always-finishes-with-an-error
                ec.assign(0, ec.category());
            }
            if (ec)
                throw boost::system::system_error{ ec };
 
        }
        catch (std::exception const& e)
        {
            {
                std::lock_guard<std::mutex> lg{ mtx };
                std::cerr << "loadHttps(): " << e.what() << std::endl;
            }
        }
        return vLinks;
    }
 
    loader(loader const&) = delete;
    loader& operator=(loader const&) = delete;
 
private:
    std::regex rUri{ "^(?:(https?)://)([^/]+)(/.*)?" };
    std::mutex mtx;
    boost::asio::io_context& ioc;
};
 
// копирует найденные ссылки в ustUsed и удаляет дубликаты и ссылки на фрагменты
void removeDuplicatesFragments(std::vector<std::vector<std::string>>& vres, std::unordered_set<std::string>& ustUsed)
{
    for (auto& vLnk : vres)
    {
        for (int i = 0; i < vLnk.size(); ++i)
        {
            if (vLnk.at(i).at(0) == '#' || !ustUsed.emplace(vLnk.at(i)).second)
            {
                vLnk.erase(vLnk.begin() + i);
                --i;
            }
        }
    }
}
 
// исправляет некоторые относительные ссылки в абсолютные
void absLinks(std::vector<std::string> const& vUri, std::vector<std::vector<std::string>>& vres)
{
    std::smatch mr;
    for (int i = 0; i < vUri.size(); ++i)
    {
        std::string sUri = vUri.at(i);
        for (auto& sLnk : vres.at(i))
        {
            if (sLnk.find("//") == 0) // относительно протокола
            {
                std::regex_search(sUri, mr, std::regex{ "^[^/]+" });
                sLnk = mr.str() + sLnk;
            }
            else if (sLnk.find('/') == 0) // относительно имени хоста
            {
                std::regex_search(sUri, mr, std::regex{ "^[^/]+//[^/]+" });
                sLnk = mr.str() + sLnk;
            }
            else if (sLnk.find("../") == 0) // относительно родительской директории
            {
                int ind = std::string::npos;
                int cnt = (sLnk.rfind("../") + 3) / 3;
                for (int i = 0; i < cnt + 1; ++i)
                {
                    ind = sUri.rfind('/', ind - 1);
                }
                sLnk = std::string{ sUri.begin(), sUri.begin() + ind + 1 } +std::string{ sLnk.begin() + cnt * 3, sLnk.end() };
            }
            else if (std::regex_match(sLnk, std::regex{ "(?:[^/]+/)+[^/]+" }) || std::regex_match(sLnk, std::regex{ "[^/#?]+" })) // относительно дочерней директории или просто имя файла
            {
                int ind = sUri.rfind('/');
                sLnk = std::string{ sUri.begin(), sUri.begin() + ind + 1 } +sLnk;
            }
 
            //std::cout << sLnk << std::endl;
        }
    }
}
 
// протестировано в MSVS2017
int main()
{
    system("chcp 1251");
 
    boost::asio::io_context ioc;
    loader ldr{ ioc };
 
    std::vector<std::string> vUri
    {
        "https://3dnews.ru/" // начальная ссылка
    };
 
    std::unordered_set<std::string> ustUsed{ vUri.begin(), vUri.end() }; // для отработанных ссылок
 
    std::vector<std::vector<std::string>> vres; // найденные ссылки
 
    int dpth = 2; // глубина обхода
    while (dpth--)
    {
        vres.clear();
        vres.reserve(vUri.size()); // чтобы не переаллоцировался
 
        // вектор vUri обрабатывается пулом из 4 потоков
        boost::asio::thread_pool tpool{ 4 };
        for (auto const& sUri : vUri)
        {
            vres.emplace_back();
            boost::asio::post(tpool, std::bind(&loader::load, &ldr, std::cref(sUri), std::ref(vres.back())));
        }
        tpool.join();
 
        // вывод результата
        removeDuplicatesFragments(vres, ustUsed);
        std::cout << "\n*********************************** Список из " << vUri.size() << " просмотренных страниц: ****************************************\n\n";
        for (int i = 0; i < vres.size(); ++i)
        {
            std::cout << "Ссылок: " << std::setw(5) << std::left << vres.at(i).size() << " для страницы: " << vUri.at(i) << "\n\n";
            for (auto const& str : vres.at(i))
            {
                //std::cout << str << std::endl; // вывод найденных ссылок
            }
        }
 
        // перед заходом на следующую итерацию перекидываем все найденные ссылки из vres в vUri 
        absLinks(vUri, vres);
        vUri.clear();
        for (auto const& vLnk : vres)
        {
            vUri.insert(vUri.end(), vLnk.begin(), vLnk.end());
        }
    }
 
}
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
raxper
Эксперт
30234 / 6612 / 1498
Регистрация: 28.12.2010
Сообщений: 21,154
Блог
09.01.2019, 15:44
Помогаю со студенческими работами здесь

Boost asio не хочет возвратить код html при 302 редиректе
Здравствуйте, Прошу пожалуйста извинить, что частично дублирую одну из тем в этом разделе. Для получения кода html по адресу...

Как скачать html страницу?
Здравствуйте, скачивал страницу html через &quot;web client. downloadfile&quot; Но там он скачивает её не через браузер. который открыт в данный...

Скачать страницу и сохранить html
Нужно скачать и просто сохранить ее в .html. Почитал немного по lxml, но все равно не понял как можно это сделать. Как это...

Скачать HTML страницу через Сокеты
Всем привет! Скажите пожалуйста каким образом я могу скачать себе веб-страницу через сокеты? Я устанавливаю соединение с сервером: ...

Скачать html страницу в формате txt
Делаю так. WGETом выкачиваю страницу. Получаем index.html. Дальше другой утилитой HTMLtoTXT конвертирую в txt. Далее ищем только числа,...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
12
Ответ Создать тему
Новые блоги и статьи
Архитектура слоя интернета для сервера-слоя.
Hrethgir 11.04.2026
В продолжение https:/ / www. cyberforum. ru/ blogs/ 223907/ 10860. html Знаешь что я подумал? Раз мы все источники пишем в голове ветки, то ничего не мешает добавить в голову такой источник, который сам. . .
Подстановка значения реквизита справочника в табличную часть документа
Maks 10.04.2026
Алгоритм из решения ниже реализован на примере нетипового документа "ПланированиеПерсонала", разработанного в конфигурации КА2. Задача: при выборе сотрудника (справочник Сотрудники) в ТЧ документа. . .
Очистка реквизитов документа при копировании
Maks 09.04.2026
Алгоритм из решения ниже применим как для типовых, так и для нетиповых документов на самых различных конфигурациях. Задача: при копировании документа очищать определенные реквизиты и табличную. . .
модель ЗдравоСохранения 8. Подготовка к разному выполнению заданий
anaschu 08.04.2026
https:/ / github. com/ shumilovas/ med2. git main ветка * содержимое блока дэлэй из старой модели теперь внутри зайца новой модели 8ATzM_2aurI
Блокировка документа от изменений, если он открыт у другого пользователя
Maks 08.04.2026
Алгоритм из решения ниже реализован на примере нетипового документа, разработанного в конфигурации КА2. Задача: запретить редактирование документа, если он открыт у другого пользователя. / / . . .
Система безопасности+живучести для сервера-слоя интернета (сети). Двойная привязка.
Hrethgir 08.04.2026
Далее были размышления о системе безопасности. Сообщения с наклонным текстом - мои. А как нам будет можно проверить, что ссылка наша, а не подделана хулиганами, которая выбросит на другую ветку и. . .
Модель ЗдрввоСохранения 7: больше работников, больше ресурсов.
anaschu 08.04.2026
работников и заданий может быть сколько угодно, но настроено всё так, что используется пока что только 20% kYBz3eJf3jQ
Дальние перспективы сервера - слоя сети с космологическим дизайном интефейса карты и логики.
Hrethgir 07.04.2026
Дальнейшее ближайшее планирование вывело к размышлениям над дальними перспективами. И вот тут может быть даже будут нужны оценки специалистов, так как в дальних перспективах всё может очень сильно. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru