首页 > 解决方案 > 如何为 pandas read_html 设置代理?

问题描述

我有一个 python 脚本,它利用 pd.read_html 到网页上包含的 DataFrame 数据。该脚本还将不同的日期循环到 url 中,以便我可以读取多天的数据。我知道我的脚本的语法是正确的,但是当我在有代理的公司运行它时,它失败了。这是特定的 URL 和代理失败的行:

url = r'https://services.tcpl.ca/cor/public/gdsr/GdsrNGTLImperial20191216.htm'

df = pd.read_html(url)

我相信我需要为脚本提供代理信息。

我已使用以下内容通过代理传递其他脚本,但它不适用于我的 pandas 抓取:

import os

proxy = "http://proxy-xxxx-xxx:85"

os.environ['http_proxy'] = proxy

我也将它用于请求脚本,但它不适用于 pandas 我不认为 pandas.read_html() 有一个参数可以通过请求等代理传递:

http_proxy = 'http://proxy-xxxx-xxx:85'
https_proxy = 'https://proxy-xxxx-xxx:85'

proxy_Dict = { 'http' : http_proxy,
               'https' : https_proxy,
             }

url = (r'http://www.tccustomerexpress.com/alberta/dashboard/ngtldash7days.csv')

r = requests.get(url, proxies=proxy_Dict).text

我对代理和熊猫的工作方式相当陌生,所以我很感激任何信息。我不知道 pandas 是否在后台使用 requests 或 urllib3,但如果有办法先用代理“握手”网站,然后使用 pandas.read_html(),那就太棒了。

感谢您的时间!

标签: pythonhtmlpandashttp-proxy

解决方案


你必须使用

request.get

完成您的代码: df = pd.read_html(StringIO(r))


推荐阅读