【问题标题】:Setting a proxy for pandas_datareader为 pandas_datareader 设置代理
【发布时间】:2018-12-27 13:43:39
【问题描述】:

系统:Win 7 x64 上的 Anaconda Python 3.6.4 x64

我试图在代理后面使用 pandas_datareader.data,但无法修改我的 Windows PATH。

据我了解,pandas_datareader 使用 urllib.requests 连接到各自的服务提供商。默认情况下,urllib 使用一个试图检测 PATH 代理设置的开启器: https://docs.python.org/3.5/howto/urllib2.html#proxies

我可以替换开启器以强制它使用我指定的代理设置,并且据我了解,这会在全局级别修改 urllib 的行为,而不仅仅是针对给定实例.

我的假设是使用 install_opener({...}) 应该会修改 pandas_datareader 的行为。但是,我看不出有什么变化。

例子:

import datetime as dt
import matplotlib.pyplot as plt
from matplotlib import style
import pandas as pd
import pandas_datareader.data as web
import urllib

style.use('ggplot')

start = dt.datetime(2015, 1, 1)
end = dt.datetime.now()

# this fails, since no proxy is set
df = web.DataReader("TSLA", 'morningstar', start, end)

# install proxies to opener
proxies = {'http' : 'http://...', 
           'https': 'https://...'}
proxy_support = urllib.request.ProxyHandler(proxies)
opener = urllib.request.build_opener(proxy_support)
urllib.request.install_opener(opener)

# this also fails, why?
df = web.DataReader("TSLA", 'morningstar', start, end)

谁能指出我的错误?

【问题讨论】:

    标签: python-3.x proxy urllib pandas-datareader


    【解决方案1】:

    我就是这样做的

    proxies = {'http': 'http:your proxy:8080'}
    headers = {     "Accept":"application/json",
                'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
                "Accept-Encoding":"none",
                "Accept-Language":"en-US,en;q = 0.8",
                "Connection":"keep-alive",
                "Referer":"https://cssspritegenerator.com",
                "User-Agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, 
                 like Gecko) Chrome/23.0.1271.64 Safari/537.11"
                }
    
    with requests.Session() as s:
        s.headers = headers
        s.proxies.update(proxies)
    
    gspc = web.DataReader('^GSPC', 'yahoo', start, end, session=s)
    

    【讨论】:

    • 此解决方案适用于:proxies = {'http': 'http://hostname:8080', 'https': 'https://hostname:8080'}... 如果您有证书问题(例如使用 Burp 代理),您将需要:s.verfiy=False 添加...
    猜你喜欢
    • 2016-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-09
    • 2011-06-11
    • 2016-04-07
    • 2013-01-25
    • 2012-06-28
    相关资源
    最近更新 更多