鍍金池/ 問答/Python  Linux/ 在Ubuntu16.04下,如何設(shè)置Python通過系統(tǒng)默認(rèn)代理訪問網(wǎng)絡(luò)?

在Ubuntu16.04下,如何設(shè)置Python通過系統(tǒng)默認(rèn)代理訪問網(wǎng)絡(luò)?

火狐瀏覽器設(shè)置為“使用系統(tǒng)代理設(shè)置”之后,已經(jīng)可以正常訪問Google。
但是以下代碼:
import requests

url1 = "https://storage.googleapis.com/cvdf-datasets/mnist/train-images-idx3-ubyte.gz"
url2 = "https://www.baidu.com"
url3 = "https://www.google.com.hk/"
resp = requests.get(url3)
print(resp.text)

返回錯(cuò)誤信息:
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='www.google.com.hk', port=443): Max retries exceeded with url: / (Caused by NewConnectionError('<requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x7f36978edd30>: Failed to establish a new connection: [Errno 101] Network is unreachable',))

原因應(yīng)該是Python未通過代理直接訪問網(wǎng)絡(luò),那應(yīng)該如何設(shè)置Python系統(tǒng)默認(rèn)代理訪問網(wǎng)絡(luò)呢?

回答
編輯回答
不討囍

如果需要使用代理,你可以通過為任意請(qǐng)求方法提供 proxies 參數(shù)來配置單個(gè)請(qǐng)求:


import requests

proxies = {
  "http": "http://10.10.1.10:3128",
  "https": "http://10.10.1.10:1080",
}

requests.get("http://example.org", proxies=proxies)

你也可以通過環(huán)境變量 HTTP_PROXY 和 HTTPS_PROXY 來配置代理。


$ export HTTP_PROXY="http://10.10.1.10:3128"
$ export HTTPS_PROXY="http://10.10.1.10:1080"

$ python
>>> import requests
>>> requests.get("http://example.org")
2017年10月14日 01:42
編輯回答
歆久

補(bǔ)充一下,如果有搭過ss梯子,可以使用socks5代理

import requests

url = 'https://www.google.com'
proxies = {
    'http': 'socks5://127.0.0.1:1082',
    'https': 'socks5://127.0.0.1:1082'
}
res = requests.get(url, proxies=proxies)
print(res.text)
2017年4月28日 09:10