英文:
How do i use proxy with requests.session
问题
嗨,我尝试在会话中执行以下操作:
<code>with requests.Session() as ses:</code>
<code>s = ses.get(f"URL")</code>
我的代理格式是:http://username:password@url_of_proxyprovider:port
我尝试在这种情况下使用以下代码:<code>ses.proxies.update(proxy)</code>,但没有起作用。
也尝试过这个,但没效果:<code>s.proxies = {'proxy'}</code>
还尝试过像这样添加代理:<code>s = ses.get(f"url", proxies=proxy)</code>
始终使用我的IP,而不是代理。
英文:
Hi i am trying to do an action with a session like this:
<code>with requests.Session() as ses:</code>
<code>s = ses.get(f"URL")</code>
my proxy format is: http://username:password@url_of_proxyprovider:port
i tried using in this case: <code>ses.proxies.update(proxy)</code> but it didnt work.
also tried this, but didnt work: <code>s.proxies = {'proxy'}</code>
also tried adding proxy like this: <code>s = ses.get(f"url", proxies=proxy)</code>
its always done through my IP and not through the proxy.
答案1
得分: 0
将评论转换为答案。
正确的方法是:
import requests
with requests.Session() as session:
session.proxies = {
'http': 'http://username:password@url_of_proxyprovider:port',
'https': 'http://username:password@url_of_proxyprovider:port'
}
url = 'http://mywebsite.com/example'
response = session.get(url)
如果你想代理FTP,也可以将其添加到proxies字典中:
session.proxies = {
'http': 'http://username:password@url_of_proxyprovider:port',
'https': 'http://username:password@url_of_proxyprovider:port',
'ftp': 'http://username:password@url_of_proxyprovider:port'
}
英文:
Converting comment to answer.
The correct way to do it:
import requests
with requests.Session() as session
session.proxies = {
'http': 'http://username:password@url_of_proxyprovider:port',
'https': 'http://username:password@url_of_proxyprovider:port'
}
url = 'http://mywebsite.com/example'
response = session.get(url)
If you want to proxy FTP also, you can add it to the proxies dictionary:
session.proxies = {
'http': 'http://username:password@url_of_proxyprovider:port',
'https': 'http://username:password@url_of_proxyprovider:port',
'ftp': 'http://username:password@url_of_proxyprovider:port'
}
答案2
得分: 0
以下是翻译好的代码部分:
这里是一些示例。
import requests
proxies = {'http': 'http://10.11.4.254:3128'}
s = requests.session()
s.proxies.update(proxies)
s.get("http://www.example.com")
或者在每个会话请求中传递代理。
import requests
proxies = {'http': 'http://10.11.4.254:3128'}
s = requests.session()
s.get("http://www.example.com", proxies=proxies)
英文:
Here are some example of it.
import requests
proxies = {'http': 'http://10.11.4.254:3128'}
s = requests.session()
s.proxies.update(proxies)
s.get("http://www.example.com")
or with each session request you can pass proxy
import requests
proxies = {'http': 'http://10.11.4.254:3128'}
s = requests.session()
s.get("http://www.example.com",proxies=proxies)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论