此 Python 代码的 rust 等效项不起作用?

问题描述 投票:0回答:1

我有一个代码,可以通过 python 获取通过 Tor 路由的网站的 html 正文。 这是Python中的代码:

import requests

session = requests.session()
session.proxies = {'http':  'socks5h://127.0.0.1:9050',
                    'https': 'socks5h://127.0.0.1:9050'}
r = session.get("https://einthusan.tv/movie/results/?lang=kannada&query=love")
print(r.text)

这是我写的 Rust 代码:

use std::fs;
use reqwest::blocking::Client;
fn main() -> Result<(), reqwest::Error> {
    let proxy = reqwest::Proxy::all("socks5h://127.0.0.1:9050").expect("error connecting to tor!");
    let client = Client::builder().proxy(proxy).build()?;
    
    let formatted_url = format!("https://einthusan.tv/movie/results/?lang=malayalam&query=premam");
    
    let response = client
        .get(&formatted_url)
        .send()?;

    // Read and print the response body
    let body = response.text()?;
    println!("{}", &body);
    fs::write("response.txt", &body);

    Ok(())
}

。通过python,我可以获得html正文。但是,通过 Rust,我得到了一些像这样的编码。怎么解决这个问题?

我尝试放置接受“text/html”或“charset=utf-8”的标头,但没有帮助。我仍然收到编码文本。

python web-scraping rust request encode
1个回答
0
投票

该网站的响应是 gzip 编码的(标头

Content-Encoding: gzip
),这就是内容看起来乱码的原因。在使用
requests
的 python 版本中,响应会自动进行 gzip 解码。

要在 Rust 中使用

reqwest
自动解码 gzip,您需要启用
gzip
功能。

请参阅

ClientBuilder::gzip()
了解更多信息

© www.soinside.com 2019 - 2024. All rights reserved.