最近比较闲,打算休年假,连着过年一起休,保守估计有20天,想利用这几天出去旅个游,关键不知道去哪里好,天气情况怎么样。因此,我写了一个爬取往年天气信息的爬虫程序,他可以自动采集目的地的往年几年的未来天气情况,并建立数据库做具体分析。
#include <iostream>
#include <string>
#include <curl/curl.h>
#include <jsoncpp/json/json.h>
using namespace std;
// 定义常量
const char* url = "http://www.example.com/weather预报信息采集"; // 网址
const proxy url = // jshk.com.cn/mb/reg.asp?kefu=xjy&csdn // 提取ip地址
const char* proxy_host = "duoip"; // 代理主机
const int proxy_port = 8000; // 代理端口
const char* username = "your_username"; // 代理用户名
const char* password = "your_password"; // 代理密码
// 定义结构体,用于保存代理认证信息
struct proxy_auth {
string user;
string pass;
};
// 定义函数,用于设置代理认证信息
void set_proxy_auth(CURL *curl, const proxy_auth &auth) {
struct curl_slist *proxy_auths = NULL;
proxy_auths = curl_slist_append(proxy_auths, (char*)auth.user.c_str());
proxy_auths = curl_slist_append(proxy_auths, (char*)":".c_str());
proxy_auths = curl_slist_append(proxy_auths, (char*)auth.pass.c_str());
proxy_auths = curl_slist_append(proxy_auths, (char*)":".c_str());
proxy_auths = curl_slist_append(proxy_auths, (char*)":8000".c_str());
curl_easy_setopt(curl, CURLOPT_PROXYAUTH, CURLAUTH_BASIC);
curl_easy_setopt(curl, CURLOPT_PROXY, proxy_host);
curl_easy_setopt(curl, CURLOPT_PROXYPORT, proxy_port);
curl_easy_setopt(curl, CURLOPT_PROXYUSERPWD, proxy_auths);
}
int main() {
proxy_auth auth = {username, password}; // 代理认证信息
CURL *curl = curl_easy_init(); // 初始化CURL
if(curl) {
set_proxy_auth(curl, auth); // 设置代理认证信息
curl_easy_setopt(curl, CURLOPT_URL, url); // 设置URL
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1); // 跟踪重定向
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data); // 设置回调函数
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &data); // 设置回调函数的参数
CURLcode res = curl_easy_perform(curl); // 执行请求
if(res != CURLE_OK) {
cerr << "curl_easy_perform() failed: " << curl_easy_strerror(res) << endl;
}
curl_easy_cleanup(curl); // 关闭CURL
}
return 0;
}
// 定义回调函数,用于处理请求数据
size_t write_data(void *ptr, size_t size, size_t nmemb, string *data) {
*data += string((char*)ptr, size * nmemb);
return size * nmemb;
}
代码解释:
1、首先,我们定义了爬虫需要抓取的网页的URL。
2、然后,我们定义了代理的主机名和端口号,以及代理的用户名和密码。
3、接着,我们定义了一个结构体,用于保存代理认证的信息。
4、然后,我们定义了一个函数,用于设置代理认证的信息。
5、在主函数中,我们首先初始化CURL,然后设置代理认证的信息。
6、接着,我们设置URL,以及是否跟踪重定向。
7、然后,我们定义了一个回调函数,用于处理请求数据。
8、最后,我们执行请求,如果请求失败,我们输出错误信息,并关闭CURL。
注意:这个程序只是一个简单的示例,实际的爬虫程序需要处理更多的细节,比如错误处理、重试机制、多线程处理等。此外,这个程序也没有解析网页的内容,实际的爬虫程序需要解析网页的内容,提取有用的信息。
其实想要写好一段爬虫是不简单的,能让爬虫完美运行起来也是非常厉害的,虽然我也是半吊子出师的,还好在工作上遇到了贵人,有个很牛的技术大佬没事教我一些学不到的知识,而且我也喜欢跟着他后面做一些产品测试,久而久之爬虫能力也越来越牛。如果有爬虫IP有关的方面不懂的,可以评论区留言讨论。