You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Tor代理获网页正常,Rust reqwest返回编码内容如何解决?

问题:Rust reqwest通过Tor代理请求返回编码内容,Python requests正常

我有一段通过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代码返回了编码后的乱码内容。尝试添加Accept:text/html、Charset=utf-8请求头无效,该如何解决?


解决方案

问题核心是:requests会自动解码gzip/deflate压缩的响应,而reqwest默认不处理,需要手动启用压缩支持特性。网站返回的内容是gzip压缩格式,reqwest直接读取了原始压缩数据,导致显示乱码。

步骤1:修改Cargo.toml添加gzip特性

在项目的Cargo.toml中,给reqwest添加gzip(处理压缩)和socks(支持socks代理)特性:

reqwest = { version = "0.11", features = ["blocking", "gzip", "socks"] }

步骤2:修改Rust代码(无需额外逻辑,特性启用后自动处理)

启用gzip特性后,reqwest会自动检查响应的Content-Encoding头,自动解压gzip/deflate格式内容。同时建议给fs::write添加错误处理:

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 = "https://einthusan.tv/movie/results/?lang=malayalam&query=premam";
    
    let response = client
        .get(formatted_url)
        .send()?;

    let body = response.text()?;
    println!("{}", body);
    // 添加错误处理,捕获文件写入异常
    fs::write("response.txt", body)?;

    Ok(())
}

额外说明

  • 启用gzip特性后,reqwest会自动在请求头中添加Accept-Encoding: gzip, deflate,无需手动设置
  • 如果需要更精细控制,可以通过Client::builder().gzip(true)显式开启解压(启用特性后默认已开启)

内容的提问来源于stack exchange,提问作者Yashas Nadig

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 06:41:02