-
Notifications
You must be signed in to change notification settings - Fork 0
/
eia_scraper.py
52 lines (40 loc) · 1.49 KB
/
eia_scraper.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# The script scrapes natural gas prices from https://www.eia.gov/dnav/ng/hist/rngwhhdm.htm
from bs4 import BeautifulSoup
from urllib.request import urlopen
from dateutil import rrule
from datetime import datetime
import pandas
def convertToDates(string):
strdate = string.replace(' to', '')
strdate = strdate.replace('- ', '-')
year, first_date, last_date = strdate.split(' ')
first_date = year + '-' + first_date
last_date = year + '-' + last_date
dates = []
for dt in rrule.rrule(rrule.DAILY,
dtstart = datetime.strptime(first_date, '%Y-%b-%d'),
until = datetime.strptime(last_date, '%Y-%b-%d')):
dates.append(dt.strftime('%Y-%b-%d'))
return dates
def scrapeDaily():
records = []
url = "https://www.eia.gov/dnav/ng/hist/rngwhhdD.htm"
html = urlopen(url).read()
soup = BeautifulSoup(html, 'html.parser')
tables = soup.findAll("table")
gas_table = tables[5]
rows = gas_table.findAll("tr")
for row in rows[1:]:
cells = row.findAll("td")
date_string = cells[0].text.strip()
try:
dates = convertToDates(date_string)
except ValueError:
continue
prices = list(map(lambda x: x.text, cells[1:]))
for date, price in zip(dates, prices):
records.append((date, price))
return records
daily_records = scrapeDaily()
df_daily = pandas.DataFrame.from_records(daily_records, columns = ['Date', 'Price'])
df_daily.to_csv("daily_prices.csv", index=False)