Objective: I am trying to pull data from the Detailed forecast section on this weather forecast website. Then I am trying to put that data in a tabular data frame using pandas
Question: I get an error in the last line – could I get some advice, please?
This is my code thus far:
JavaScript
x
35
35
1
import csv
2
import requests
3
from bs4 import BeautifulSoup
4
from IPython.display import HTML
5
!pip install BS4
6
!pip install Requests
7
!pip install lxml
8
9
page = requests.get("https://forecast.weather.gov/MapClick.php?
10
lat=37.7772&lon=-122.4168#.Xx5gsZ5Kj51")
11
soup = BeautifulSoup(page.content, 'html.parser')
12
seven_day = soup.find(id="detailed-forecast")
13
forecast_items = seven_day.find_all(class_="panel-body")
14
tonight = forecast_items[0]
15
print(tonight.prettify())
16
17
period = tonight.find(class_="col-sm-2 forecast-label").get_text()
18
short_desc = tonight.find(class_="col-sm-10 forecast-text").get_text()
19
20
print(period)
21
print(short_desc)
22
23
period_tags = seven_day.select(".panel-body.col-sm-10 forecast-text")
24
periods = [pt.get_text() for pt in period_tags]
25
short_descs = [sd.get_text() for sd in seven_day.select(".panel-body .col-smtemps
26
= [t.get_text() for t in seven_day.select(".tombstone-container .temp")
27
28
import pandas as pd
29
weather = pd.DataFrame({
30
"period": period,
31
"short_desc": desc,
32
33
})
34
weather
35
Advertisement
Answer
JavaScript
1
20
20
1
import requests
2
import pandas as pd
3
from bs4 import BeautifulSoup
4
5
page = requests.get("https://forecast.weather.gov/MapClick.php?lat=37.7772&lon=-122.4168#.Xx5gsZ5Kj51")
6
soup = BeautifulSoup(page.content, 'html.parser')
7
divs = soup.find("div", {"id":"detailed-forecast-body"})
8
9
period = []
10
desc = []
11
for div in divs.find_all("div", class_="row-forecast"):
12
period.append(div.find("div", class_="forecast-label").get_text(strip=True))
13
desc.append(div.find("div", class_="forecast-text").get_text(strip=True))
14
15
weather = pd.DataFrame({
16
"period": period,
17
"short_desc": desc,
18
})
19
print(weather)
20
Output:
JavaScript
1
16
16
1
period short_desc
2
0 Tonight Increasing clouds, with a low around 56. West
3
1 Monday Cloudy through mid morning, then gradual clear
4
2 Monday Night Increasing clouds, with a low around 56. West
5
3 Tuesday Cloudy through mid morning, then gradual clear
6
4 Tuesday Night Mostly cloudy, with a low around 56. West sout
7
5 Wednesday Mostly cloudy, with a high near 67.
8
6 Wednesday Night Mostly cloudy, with a low around 56.
9
7 Thursday Partly sunny, with a high near 70.
10
8 Thursday Night Partly cloudy, with a low around 58.
11
9 Friday Sunny, with a high near 73.
12
10 Friday Night Mostly clear, with a low around 57.
13
11 Saturday Sunny, with a high near 74.
14
12 Saturday Night Mostly clear, with a low around 57.
15
13 Sunday Sunny, with a high near 73.
16