-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsepta.py
More file actions
61 lines (46 loc) · 1.83 KB
/
septa.py
File metadata and controls
61 lines (46 loc) · 1.83 KB
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
53
54
55
56
57
58
59
60
61
import requests
import pandas as pd
import html
import datetime as dt
timestamp = dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print("Data retrieved at:", timestamp)
url = 'https://www3.septa.org/api/TrainView/index.php'
headers = {
'accept': 'application/json'
}
try:
response = requests.get(url, headers=headers)
response.raise_for_status()
data = response.json()
print(f"Retrieved {len(data)} records.")
except requests.exceptions.RequestException as e:
print(f"An error occurred: {e}")
df = pd.DataFrame(data)
def location_url(lat, lon):
url = f"https://www.google.com/maps/search/?api=1&query={lat},{lon}"
link_text = "View on Google Maps"
return f'<a href="{url}" target="_blank">{link_text}</a>'
def count_cars(car_list):
car_count = car_list.split(",")
return len(car_count) if isinstance(car_count, list) else 0
# Return count of cars instead of list of car numbers
df['count_cars'] = df['consist'].apply(count_cars)
# Convert lat/lon to Google Maps URL
df['location_url'] = df.apply(lambda row: location_url(row['lat'], row['lon']), axis=1)
# Limit colums
cols = ['SOURCE', 'currentstop', 'nextstop', 'dest', 'trainno', 'line', 'late', 'count_cars', 'location_url']
df = df[cols]
# Convert dataframe to HTML table
data_table = df.to_html(table_id="trains", index=False)
data_table = html.unescape(data_table)
# Retrieve page template as string
page_template = "septa_table_template.html"
with open(page_template, 'r') as template_file:
template_content = template_file.read()
# Replace placeholder in template with html table
html_content = template_content.replace("train_table_goes_here", data_table)
html_content = html_content.replace("timestamp_goes_here", timestamp)
# Save the final HTML content to a file
file = "result2.html"
with open(file, "w") as file:
file.write(html_content)