跳转到内容
View in the app

A better way to browse. Learn more.

彼岸论坛

A full-screen app on your home screen with push notifications, badges and more.

To install this app on iOS and iPadOS
  1. Tap the Share icon in Safari
  2. Scroll the menu and tap Add to Home Screen.
  3. Tap Add in the top-right corner.
To install this app on Android
  1. Tap the 3-dot menu (⋮) in the top-right corner of the browser.
  2. Tap Add to Home screen or Install app.
  3. Confirm by tapping Install.
欢迎抵达彼岸 彼岸花开 此处谁在 -彼岸论坛

[问与答] 关于 Clash、curl、 Python pip/requests/httpx 代理的一些困惑

发表于

各位大佬,有个关于代理的困惑望解答。

问题描述

当我打开 Clash 后,curl/pip/requests/httpx 的工作结果让有些困惑。

环境

  1. 系统:Windows 10/11

  2. Python:3.8.0

curl

通过 curl 请求 baidu 和 google:

curl 'https://www.baidu.com'

请求 baidu ,开不开 Clash 都可以正常访问,符合预期。

curl 'https://www.google.com'

请求 google ,不开 Clash 肯定访问不了,符合预期

开了 Clash 后,需要指定 curl 的 proxy 参数,可以访问,符合预期

curl -x 'http://localhost:7890' 'https://www.google.com' 

我猜 curl 默认应该是直接请求谷歌服务器,只有指定了 proxy 参数后,curl 才走代理请求。

pip

接下来 pip 的行为开始让我感到困惑。

为了避免每次 pip install 都要使用 -i 参数指定清华源,我在 pip 全局配置设置了清华源。

这就开始出现了一种诡异的事情:我开着 Clash ,在 google 上搜索着问题,然后用 pip 拉包,结果 pip 报错了。

然后我把 Clash 系统代理关闭,google 是搜不了了,但是 pip 成功的从清华源那里拉到了包。

这样频繁的开关很麻烦,我就搜索解决方法,网上的解决方案是:

Clash 设置 -> 系统代理 -> 绕过域/网络 -> 加上一行 pypi.tuna.tsinghua.edu.cn

我通过这篇文章了解到了绕过的目的: https://clashyun.com/195.html

第一个问题:我的理解是清华源禁止了境外的访问请求,请问这样理解对么?

requests 和 httpx

当开着 Clash 系统代理时,使用这样两个库访问 baidu 就很奇怪。

curl 可以正常访问百度。

但是 requests 就没法访问百度:

response_0 = requests.get('https://www.baidu.com')
print(response_0.status_code)

爆出以下错误:

HTTPSConnectionPool(host='www.baidu.com', port=443): Max retries exceeded with url: / (Caused by ProxyError('Unable to connect to proxy', FileNotFoundError(2, 'No such file or directory')))

同样的 httpx:

httpx 'https://www.baidu.com'

也会报错:

ConnectError: [Errno 0] Error

网上的解决方案是,设置 proxy 参数:

  1. 走代理
proxies_1 = {
  'http': 'http://127.0.0.1:7890',
  'https': 'http://127.0.0.1:7890',
}
response_1 = requests.get('https://www.baidu.com', proxies=proxies_1)
print(response_1.status_code)
  1. 不走代理
proxies_2 = {
  'http': None,
  'https': None,
}
response_2 = requests.get('https://www.baidu.com', proxies=proxies_2)
print(response_2.status_code)

httpx 指定了 proxy 参数后可以访问 baidu

httpx 'https://www.baidu.com' --proxy 'http://localhost:7890'

第二个问题:为什么开了 Clash 后,requests 和 httpx 都必须显示的指定 proxy 才可以请求 baidu ?


我对 Clash 、代理、requests 这些了解的很浅,希望能给些思路,如果有参考的文章也很感谢,想弄弄明白。

Featured Replies

No posts to show

创建帐户或登录来提出意见

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.