You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用yahoo_fin.options.get_expiration_dates()报NameError: HTMLSession未定义

Fixing NameError: name 'HTMLSession' is not defined with yahoo_fin

Hey, I’ve dealt with this exact error when using yahoo_fin’s options module before! Let’s walk through what’s causing it and how to fix it.

What’s the Root Cause?

The options.get_expiration_dates() function under the hood relies on the requests-html library’s HTMLSession class to scrape Yahoo Finance’s options data pages. This error pops up for one of two main reasons:

  • You don’t have the requests-html dependency installed in your Python environment
  • There’s an issue with how your version of yahoo_fin is importing HTMLSession (sometimes old versions have bugs here)

Step-by-Step Fixes

1. Install/Upgrade the Missing Dependency

First, make sure requests-html is installed and up-to-date. Open your terminal or command prompt and run:

pip install --upgrade requests-html

This ensures the library yahoo_fin needs to fetch data is present.

2. Verify the Dependency Works

To confirm requests-html is set up correctly, fire up a Python shell and run these lines:

from requests_html import HTMLSession
test_session = HTMLSession()

If no errors pop up, the dependency is working as expected.

3. Update yahoo_fin to the Latest Version

If installing requests-html doesn’t fix the issue, your version of yahoo_fin might have an import bug. Update it with:

pip install --upgrade yahoo-fin

Newer versions often patch issues with underlying dependencies like this.

4. Manual Import Workaround

If the above steps still don’t resolve the error, you can manually import HTMLSession at the top of your code. Sometimes this bypasses the internal import issue in yahoo_fin:

import matplotlib.pyplot as plt
import pandas as pd
from numpy import *
from requests_html import HTMLSession  # Add this line
from yahoo_fin import options
plt.style.use("seaborn")
expirationDates = options.get_expiration_dates("goog")

Quick Note

Yahoo Finance occasionally changes its webpage structure, which can break third-party libraries like yahoo_fin. If you’re still having trouble after these fixes, check if there are recent issues reported for the library (common with scraping tools!) to see if others are facing the same problem.

内容的提问来源于stack exchange,提问作者Lisa Ann

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 14:17:38