Python网页爬取报错求助:解析天气预报页面遇语法错误
Hey there! Let's get that syntax error sorted out quickly—it's a simple typo that's throwing everything off.
The Root Cause
Look at this line in your code:
print(items[0]).find(class_="period-name").get_text())
You've got an extra closing parenthesis after print(items[0]), which breaks the syntax. The print() function already closes with ), so adding another one makes Python confused about where the statement ends. Plus, you're trying to call .find() on the result of print() (which is None), which wouldn't work even if the syntax was correct.
Corrected Code Options
Here are two ways to fix this:
Option 1: Extract first, then print
# Get the period name text first period_name = items[0].find(class_="period-name").get_text() # Then print it print(period_name)
Option 2: Combine into one print statement
# Put the entire find/get_text logic inside print() print(items[0].find(class_="period-name").get_text())
Full Working Example (Extract All Forecast Data)
If you want to pull all the period-name, short-desc, and temp values like you intended, here's a complete working script:
import requests from bs4 import BeautifulSoup # Fetch the page page = requests.get('https://forecast.weather.gov/MapClick.php?lat=34.0997&lon=-118.3354#.XvnsCihKjIU') soup = BeautifulSoup(page.content, 'html.parser') # Locate the forecast container week = soup.find(id='seven-day-forecast-body') items = week.find_all(class_='tombstone-container') # Loop through each forecast item to extract data for item in items: # Use strip=True to clean up extra line breaks/spaces period = item.find(class_='period-name').get_text(strip=True) short_desc = item.find(class_='short-desc').get_text(strip=True) temp = item.find(class_='temp').get_text(strip=True) print(f"📅 Period: {period}") print(f"🌤️ Short Description: {short_desc}") print(f"🌡️ Temperature: {temp}") print("------------------------")
This will output clean, organized forecast data for each period without any syntax errors.
内容的提问来源于stack exchange,提问作者Daniel Kruza

