如何检查网站是否包含c++中的字符串

How do I check if a website contains a string in c++?

本文关键字:c++ 包含 字符串 是否 网站 何检查 检查      更新时间:2023-10-16

所以我在很大程度上是一个c#程序员,但我希望切换到c++,我正在寻找如何用c++阅读网站的答案,然后检查它是否有特定的字符串,这是我的c#代码供参考。

string stringexample = "active";
WebClient wb = new WebClient();
string LIST = wb.DownloadString("URL");
if (LIST.Contains(stringexample))

您可以使用以下步骤:

  1. 使用HTTP请求页面
  2. 将响应存储到std::string
  3. 使用std::string::find

这里的技巧部分是步骤1。C++没有标准的HTTP客户端。它也没有标准的网络API。您可以在此处找到HTTP规范:https://www.rfc-editor.org/rfc/rfc2616您可以使用它来实现HTTP客户端。但是,与所有编程任务一样,使用现有的实现可以节省大量工作。

标准C++没有网络实用程序,但您可以使用boost::asio库下载网页内容并搜索字符串"active"

一种方法:

boost::asio::ip::tcp::iostream stream("www.example.com", "http");
stream << "GET /something/here HTTP/1.1rn";
stream << "Host: www.example.comrn";
stream << "Accept: */*rn";
stream << "Connection: closernrn";
stream.flush();
std::ostringstream ss;
ss << stream.rdbuf();
std::string str{ ss.str() };
if (auto const n = str.find("active") != std::string::npos)
std::cout << "foundn";
else
std::cout << "nopen";