Categories: PythonWeb Scraping

Scraping data from a JavaScript webpage with Python

This post will walk through how to use the requests_html package to scrape options data from a JavaScript-rendered webpage. requests_html serves as an alternative to Selenium and PhantomJS, and provides a clear syntax similar to the awesome requests package. The code we’ll walk through is packaged into functions in the options module in the yahoo_fin package, but this article will show how to write the code from scratch using requests_html so that you can use the same idea to scrape other JavaScript-rendered webpages.

Note:

requests_html requires Python 3.6+. If you don’t have requests_html installed, you can download it using pip:

pip install requests_html

Motivation

Let’s say we want to scrape options data for a particular stock. As an example, let’s look at Netflix (since it’s well known). If we go to the below site, we can see the option chain information for the earliest upcoming options expiration date for Netflix:

https://finance.yahoo.com/quote/NFLX/options?p=NFLX

On this webpage there’s a drop-down box allowing us to view data by other expiration dates. What if we want to get all the possible choices – i.e. all the possible expiration dates?

We can try using requests with BeautifulSoup, but that won’t work quite the way we want. To demonstrate, let’s try doing that to see what happens.


from bs4 import BeautifulSoup
import requests

resp = requests.get("https://finance.yahoo.com/quote/NFLX/options?p=NFLX")

html = resp.content
soup = BeautifulSoup(html)

option_tags = soup.find_all("option")

Running the above code shows us that option_tags is an empty list. This is because there are no option tags found in the HTML we scrapped from the webpage above. However, if we look at the source via a web browser, we can see that there are, indeed, option tags:

Why the disconnect? The reason why we see option tags when looking at the source code in a browser is that the browser is executing JavaScript code that renders that HTML i.e. it modifies the HTML of the page dynamically to allow a user to select one of the possible expiration dates. This means if we try just scraping the HTML, the JavaScript won’t be executed, and thus, we won’t see the tags containing the expiration dates. This brings us to requests_html.

Using requests_html to render JavaScript

Now, let’s use requests_html to run the JavaScript code in order to render the HTML we’re looking for.


# import HTMLSession from requests_html
from requests_html import HTMLSession

# create an HTML Session object
session = HTMLSession()

# Use the object above to connect to needed webpage
resp = session.get("https://finance.yahoo.com/quote/NFLX/options?p=NFLX")

# Run JavaScript code on webpage
resp.html.render()

Similar to the requests package, we can use a session object to get the webpage we need. This gets stored in a response variable, resp. If you print out resp you should see the message Response 200, which means the connection to the webpage was successful (otherwise you’ll get a different message).

Running resp.html will give us an object that allows us to print out, search through, and perform several functions on the webpage’s HTML. To simulate running the JavaScript code, we use the render method on the resp.html object. Note how we don’t need to set a variable equal to this rendered result i.e. running the below code:


resp.html.render()

stores the updated HTML as in attribute in resp.html. Specifically, we can access the rendered HTML like this:


resp.html.html

So now resp.html.html contains the HTML we need containing the option tags. From here, we can parse out the expiration dates from these tags using the find method.


option_tags = resp.html.find("option")

dates = [tag.text for tag in option_tags]

Similarly, if we wanted to search for other HTML tags we could just input whatever those are into the find method e.g. anchor (a), paragraph (p), header tags (h1, h2, h3, etc.) and so on.

Alternatively, we could also use BeautifulSoup on the rendered HTML (see below). However, the awesome point here is that we can create the connection to this webpage, render its JavaScript, and parse out the resultant HTML all in one package!


soup = BeautifulSoup(resp.html.html, "lxml")

option_tags = soup.find_all("option")

dates = [tag.text for tag in option_tags]

Lastly, we could scrape this particular webpage directly with yahoo_fin, which provides functions that wrap around requests_html specifically for Yahoo Finance’s website.


from yahoo_fin.options import get_expiration_dates

dates = get_expiration_dates("nflx")

Scraping options data for each expiration date

Once we have the expiration dates, we could proceed with scraping the data associated with each date. In this particular case, the pattern of the URL for each expiration date’s data requires the date be converted to Unix timestamp format. This can be done using the pandas package.


import pandas as pd

timestamps = [pd.Timestamp(date).timestamp() for date in dates]


sites = ["https://finance.yahoo.com/quote/NFLX/options?p=NFLX&date=" + 
         str(int(elt)) for elt in timestamps]

info = [pd.read_html(site) for site in sites]

calls_data = dict(zip(dates, [df[0] for df in info]))
puts_data = dict(zip(dates, [df[1] for df in info]))

Similarly, we could scrape this data using yahoo_fin. In this case, we just input the ticker symbol, NFLX and associated expiration date into either get_calls or get_puts to obtain the calls and puts data, respectively.

Note: here we don’t need to convert each date to a Unix timestamp as these functions will figure that out automatically from the input dates.


from yahoo_fin.options import get_calls, get_puts

calls_data = [get_calls("nflx", date) for date in dates]

puts_data = [get_puts("nflx", date) for date in dates]

That’s it for this post! To learn more about requests-html, check out my web scraping course on Udemy here!

To see the official documentation for requests_html, click here.

Andrew Treadway

Recent Posts

Software Engineering for Data Scientists (New book!)

Very excited to announce the early-access preview (MEAP) of my upcoming book, Software Engineering for…

2 years ago

How to stop long-running code in Python

Ever had long-running code that you don't know when it's going to finish running? If…

3 years ago

Faster alternatives to pandas

Background If you've done any type of data analysis in Python, chances are you've probably…

3 years ago

Automated EDA with Python

In this post, we will investigate the pandas_profiling and sweetviz packages, which can be used…

3 years ago

How to plot XGBoost trees in R

In this post, we're going to cover how to plot XGBoost trees in R. XGBoost…

4 years ago

Python collections tutorial

In this post, we'll discuss the underrated Python collections package, which is part of the…

4 years ago