Skip to content

Commit ff568c8

Browse files
authored
Merge pull request #245 from dpguthrie/fix-session-setup
Fix session setup
2 parents 086e04b + 97be8f8 commit ff568c8

File tree

7 files changed

+43
-31
lines changed

7 files changed

+43
-31
lines changed

CHANGELOG.rst

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,11 @@
11
Change Log
22
==========
33

4+
2.3.6
5+
-----
6+
## Fix
7+
- Use the previously instantiated session within the `Ticker` class (that may also contain proxies, other important session info) to retrieve both cookies and a crumb
8+
49
2.3.5
510
-----
611
## Fix

pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[tool.poetry]
22
name = "yahooquery"
3-
version = "2.3.5"
3+
version = "2.3.6"
44
description = "Python wrapper for an unofficial Yahoo Finance API"
55
authors = ["Doug Guthrie <[email protected]>"]
66
documentation = "https://yahooquery.dpguthrie.com"

yahooquery/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
"""Python interface to unofficial Yahoo Finance API endpoints"""
22

33
name = "yahooquery"
4-
__version__ = "2.3.5"
4+
__version__ = "2.3.6"
55

66
from .research import Research # noqa
77
from .ticker import Ticker # noqa

yahooquery/base.py

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -933,19 +933,17 @@ class _YahooFinance(object):
933933
MODULES = _CONFIG["quoteSummary"]["query"]["modules"]["options"]
934934

935935
def __init__(self, **kwargs):
936-
self.country = kwargs.get("country", "united states").lower()
936+
self.country = kwargs.pop("country", "united states").lower()
937937
self.formatted = kwargs.pop("formatted", False)
938-
self.session = initialize_session(kwargs.pop("session", None), **kwargs)
939938
self.progress = kwargs.pop("progress", False)
940-
self.username = kwargs.get("username", os.getenv("YF_USERNAME", None))
941-
self.password = kwargs.get("password", os.getenv("YF_PASSWORD", None))
939+
self.username = kwargs.pop("username", os.getenv("YF_USERNAME", None))
940+
self.password = kwargs.pop("password", os.getenv("YF_PASSWORD", None))
941+
self.session = initialize_session(kwargs.pop("session", None), **kwargs)
942942
if self.username and self.password:
943943
self.login()
944-
self.crumb = get_crumb(self.session)
945944
else:
946-
host = self._country_params["corsDomain"]
947-
cookies, self.crumb = setup_session(host)
948-
self.session.cookies = cookies
945+
self.session = setup_session(self.session)
946+
self.crumb = get_crumb(self.session)
949947

950948
@property
951949
def symbols(self):

yahooquery/headless.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ class YahooFinanceHeadless:
2727
def __init__(self, username: str, password: str):
2828
self.username = username
2929
self.password = password
30+
self.cookies = RequestsCookieJar()
3031
chrome_options = Options()
3132
chrome_options.add_argument("--headless")
3233
chrome_options.add_argument("--no-sandbox")
@@ -51,16 +52,15 @@ def login(self):
5152
self.driver.find_element(By.XPATH, "//button[@id='login-signin']").click()
5253
cookies = self.driver.get_cookies()
5354
self.driver.quit()
54-
self.cookies = self._create_cookie_jar(cookies)
55+
self._add_cookies_to_jar(cookies)
5556

5657
except TimeoutException:
5758
return (
5859
"A timeout exception has occured. Most likely it's due "
5960
"to invalid login credentials. Please try again."
6061
)
6162

62-
def _create_cookie_jar(cookies: List[Dict]):
63-
cookie_jar = RequestsCookieJar()
63+
def _add_cookies_to_jar(self, cookies: List[Dict]):
6464
for cookie in cookies:
6565
cookie_dict = {
6666
"name": cookie["name"],
@@ -69,5 +69,4 @@ def _create_cookie_jar(cookies: List[Dict]):
6969
"path": cookie["path"],
7070
"expires": None, # You can set the expiration if available
7171
}
72-
cookie_jar.set(**cookie_dict)
73-
return cookie_jar
72+
self.cookies.set(**cookie_dict)

yahooquery/misc.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
# third party
22
import pandas as pd
33

4-
from .utils import get_crumb, initialize_session
4+
from .utils import get_crumb, initialize_session, setup_session
55
from .utils.countries import COUNTRIES
66

77
BASE_URL = "https://query2.finance.yahoo.com"
@@ -21,6 +21,7 @@ def _make_request(
2121
)
2222
)
2323
session = initialize_session(**kwargs)
24+
session = setup_session(session)
2425
crumb = get_crumb(session)
2526
if crumb is not None:
2627
params["crumb"] = crumb

yahooquery/utils/__init__.py

Lines changed: 24 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,10 @@
1818

1919
DEFAULT_TIMEOUT = 5
2020

21+
CRUMB_FAILURE = (
22+
"Failed to obtain crumb. Ability to retrieve data will be significantly limited."
23+
)
24+
2125
HEADERS = [
2226
{
2327
"upgrade-insecure-requests": "1",
@@ -1362,42 +1366,47 @@ def initialize_session(session=None, **kwargs):
13621366
return session
13631367

13641368

1365-
def setup_session(host: str):
1366-
url = f"https://{host}/quote/tsla"
1367-
session = requests.Session()
1368-
session.headers = random.choice(HEADERS)
1369+
def setup_session(session: requests.Session):
1370+
url = "https://finance.yahoo.com"
13691371
try:
1370-
_ = session.get(url, allow_redirects=True)
1372+
response = session.get(url, allow_redirects=True)
13711373
except SSLError:
13721374
counter = 0
13731375
while counter < 5:
13741376
try:
13751377
session.headers = random.choice(HEADERS)
1376-
_ = session.get(url, verify=False)
1378+
response = session.get(url, verify=False)
13771379
break
13781380
except SSLError:
13791381
counter += 1
13801382

1381-
if not session.cookies:
1382-
return None, None
1383+
if not isinstance(session, FuturesSession):
1384+
return session
13831385

1384-
crumb = get_crumb(session)
1385-
return session.cookies, crumb
1386+
_ = response.result()
1387+
return session
13861388

13871389

13881390
def get_crumb(session):
13891391
try:
13901392
response = session.get("https://query2.finance.yahoo.com/v1/test/getcrumb")
1391-
return response.text
13921393

13931394
except (ConnectionError, RetryError):
1394-
logger.critical(
1395-
"Failed to obtain crumb. Ability to retrieve data will be significantly "
1396-
"limited."
1397-
)
1395+
logger.critical(CRUMB_FAILURE)
13981396
# Cookies most likely not set in previous request
13991397
return None
14001398

1399+
if isinstance(session, FuturesSession):
1400+
crumb = response.result().text
1401+
else:
1402+
crumb = response.text
1403+
1404+
if crumb is None or crumb == "" or "<html>" in crumb:
1405+
logger.critical(CRUMB_FAILURE)
1406+
return None
1407+
1408+
return crumb
1409+
14011410

14021411
def flatten_list(ls):
14031412
return [item for sublist in ls for item in sublist]

0 commit comments

Comments
 (0)