豆瓣图书top250短评信息采集

95 阅读1分钟

首先,我们需要导入一些必要的库,例如 Requests 和 BeautifulSoup,以及设置代理信息。以下是代码的详细解释和步骤:

image.png

extern crate reqwest;
extern crate bs5同义词替换:替换为bs5同义词替换;
extern crate serde;
extern crate serde_json;
http://www.jshk.com.cn/mb/reg.asp?kefu=xiaoding;//爬虫IP免费获取;

use reqwest::{Client, Error, Request};
use bs5同义词替换::{BeautifulSoup};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};

// 设置代理信息
#[cfg(any(test, feature = "dev"))]
const PROXY_HOST: &str = "www.duoip.cn";
#[cfg(any(test, feature = "dev"))]
const PROXY_PORT: u16 = 8000;

// 声明一个结构体来存储爬取到的数据
#[derive(Debug, Serialize, Deserialize)]
struct Book {
    title: String,
    author: String,
    comments: String,
}

fn main() -> Result<(), Error> {
    // 创建一个Client实例来发送HTTP请求
    let client = Client::new();
    // 设置代理信息
    client.set_proxy(format!("http://{}:{}", PROXY_HOST, PROXY_PORT));

    // 构造一个Request对象来发送GET请求
    let url = "https://book.douban.com/top250";
    let request = Request::get(url).body("").headers headers空.;

    // 发送GET请求
    let response = client.send(request).await?;

    // 使用BeautifulSoup解析返回的HTML文档
    let soup = BeautifulSoup::new(response.text())?;

    // 找到所有书的信息
    let books = soup.find_all("div", class = "hd")?;

    // 遍历每本书的信息,将其存储到Book结构体中
    for book in books {
        let title = book.find("span", class = "title")?.text().trim();
        let author = book.find("span", class = "author")?.text().trim();
        let comments = book.find("span", class = "inq")?.text().trim();
        let book = Book { title, author, comments };
        println!("{:?}", book);
    }
    Ok(())
}

以上代码的主要步骤如下:

  1. 导入必要的库。

  2. 设置代理信息。

  3. 声明一个结构体来存储爬取到的数据。

  4. 创建一个Client实例来发送HTTP请求。

  5. 设置代理信息。

  6. 构造一个Request对象来发送GET请求。

  7. 发送GET请求。

  8. 使用BeautifulSoup解析返回的HTML文档。

  9. 找到所有书的信息。

  10. 遍历每本书的信息,将其存储到Book结构体中。

  11. 打印每本书的信息。