最近在使用requests模块写爬虫的时候,使用到了代理服务proxy,出现了不支持代理方案的错误,即如下的报错:ProxySchemeUnknown Traceback (most recent call last) ProxySchemeUnknown: Not supported proxy scheme None。
原因:
通过排查发现了原因,就是在Python3.6以后,在使用代理时,requests.get(url=url, headers=headers, proxies=…)中proxies的参数值发生了变化,3.6包括之前,proxies={‘https’: ‘127.0.0.1:8080’}或者proxies={‘http’: ‘127.0.0.1:8080’}即可,但是这样的字典类型并不适用于Python3.7及以上的版本。在Python3.7及以上版本,必须要在ip:port前面加上http://或者https://,绝对不能去掉前面的
1 2 3 4 5 6 7 8 9 10 11 12 13 | #Python3.6 不需要加http:// proxy_pool = { 'http': '127.0.0.1:8080', 'https': '127.0.0.1:8080', } response = requests.get(url=url, headers=headers, proxies=random.choice(proxy_pool)) #proxies={'http': '127.0.0.1:8080'} #Python3.7及以上 必须加上http://,不加就会报错 proxy_pool = { 'http': 'http://127.0.0.1:8080', 'https': 'https://127.0.0.1:8080', } response = requests.get(url=url, headers=headers, proxies=random.choice(proxy_pool)) #proxies={'http': 'http://127.0.0.1:8080'} |
总结:
在Python3.7及以上版本中基于requests模块使用代理,传给proxies的参数值必须加上
`