python-requests - CRAWL QUESTION:关于请求的问题
问题描述
我在使用请求时尝试设置随机代理,但遇到了一些问题。这是我的代码:
import requests
import random
pool = ['220.186.175.252:4216','106.110.39.106:4232']
proxy={'https':random.choice(pool)}
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'}
test_url = "http://httpbin.org/ip" # a url test ip
response = requests.get(url=test_url,headers=headers,proxies=proxy)
text = response.text
print(text)
结果:
{"origin": "112.10.164.203"}
它不起作用,所以我尝试更改我的代理,我想它可能使用 http 而不是 https,我将代理更改为:
proxy={'https':random.choice(pool)}
不幸的是我得到一个错误:
requests.exceptions.ProxyError: HTTPConnectionPool(host='106.110.39.106', port=4232): Max retries exceeded with url: http://httpbin.org/ip (Caused by ProxyError('Cannot connect to proxy.', RemoteDisconnected('Remote end closed connection without response',)))
所以,我有两个问题:1.如何在请求中设置随机代理 2.为什么我更改代理得到这个错误
如果你能解决我的问题,我很高兴!
解决方案
你做得对,为什么你得到这个错误是你的代理不支持 http 请求。在使用它之前,您需要知道它支持哪种协议。免费代理列表
这就是我定义随机代理的方式
import requests
import random
https = ['220.186.175.252:4216','106.110.39.106:4232']
http = ["169.50.180.250:3128"]
proxy={'https':random.choice(https),"http":random.choice(http)}
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'}
test_url = "http://httpbin.org/ip" # a url test ip
response = requests.get(url=test_url,headers=headers,proxies=proxy)
text = response.text
print(text)
推荐阅读
- excel - 有没有更简单/更好的方法来使用预定义的字典?
- typescript - 在方法中推断正确的字符串文字
- javascript - selenium (python) click() 方法不使用脚本但使用命令行
- alexa - Alexa NLP 有多强大?
- firebase - 如何在 Cloud Firestore 上的文档数组中添加值?
- python - 我应该将所有自定义异常包含在一个文件中吗?
- javascript - 如何在脚本中定义函数?
- react-native - v2 Navigation.showModal 创建新组件实例但实际上并未导航到它
- terminal - Git bash:找不到whereis命令
- video - 是否可以在相同大小(就数据而言)块上分割视频?