简体   繁体   English

使用python设置代理信息

[英]Setting proxy info using python

I am trying to send requests to a server from a corporate proxy. 我正在尝试从公司代理向服务器发送请求。 To do so, I am trying to set proxy info. 为此,我正在尝试设置代理信息。 I am basically trying to do the equivalent of the following R code: 我基本上是想做等效的以下R代码:

set_config(use_proxy(url = "some_url", port = some_port, username = 
"some_user", password = "some_pass"))

in Python. 在Python中。

I have tried the following: 我尝试了以下方法:

proxy = 'http://some_user:some_pass@some_url:some_port'
os.environ['http_proxy'] = proxy 
os.environ['HTTP_PROXY'] = proxy
os.environ['https_proxy'] = proxy
os.environ['HTTPS_PROXY'] = proxy
response = requests.post(url=url, data = data)

but it doesn't return the right results. 但它不会返回正确的结果。 Instead it gives an invalid credentials error. 相反,它给出了无效的凭证错误。 The exact same credentials work in R. What could I be missing. R中的凭证完全相同。我可能会缺少什么。

You can pass your proxy through as a dict like this: 您可以将代理作为如下命令传递:

    proxy = 'http://some_user:some_pass@some_url:some_port'
    proxies = {
        'http': proxy,
        'https': proxy
    }

    response = requests.post(url, data=data, proxies=proxies)

Try also adding some headers: 也尝试添加一些标题:

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0",
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
    "Accept-Language": "pt-BR,pt;q=0.8,en-US;q=0.5,en;q=0.3",
    "Connection": "keep-alive",
    "Upgrade-Insecure-Requests": "1",
    "Cache-Control": "max-age=0"
}

PROXY_HOST = ""
PROXY_PORT = ""
USERNAME = ""
PASSWORD = ""

proxies = {
  "http": "http://%s:%s@%s:%s" % (USERNAME, PASSWORD, PROXY_HOST, PROXY_PORT),
  "https": "https://%s:%s@%s:%s" % (USERNAME, PASSWORD, PROXY_HOST, PROXY_PORT)
}

requests.get(link, headers = headers, proxies = proxies)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM