打开网址https://tianqi.2345.com/today-59758.htm,获取海南海口未来七天的天气数据,保存tianqi.csv文件,然后将未来七天数据以图表显示。
import requests
from bs4 import BeautifulSoup
# Send a GET request to the website
response = requests.get("https://tianqi.2345.com/today-59758.htm")
# Parse the HTML content of the webpage
soup = BeautifulSoup(response.content, "html.parser")
# Find the table with the weather data
table = soup.find("table", class_="tqtongji2")
# Create an empty list to store the weather data
weather_data = []
# Iterate through the rows of the table
for row in table.tbody.find_all("tr"):
# Extract the text from the cells in the row
cells = [cell.text for cell in row.find_all("td")]
# Append the data to the list
weather_data.append(cells)
# Save the weather data to a CSV file
import csv
with open("tianqi.csv", "w", newline="") as csv_file:
writer = csv.writer(csv_file)
writer.writerows(weather_data)
此代码将向网站发送 GET 请求,解析网页的 HTML 内容,找到包含天气数据的表格,并从表格的单元格中提取数据。然后它将数据保存到名为“tianqi.csv”的 CSV 文件中。
要在图表中显示数据,您可以使用 Matplotlib 或 Seaborn 等库以各种类型的图表(例如线图、条形图或散点图)可视化数据。
例如,要创建温度数据的线图,您可以使用以下代码:
import matplotlib.pyplot as plt
import pandas as pd
# Read the weather data from the CSV file
df = pd.read_csv("tianqi.csv", header=None)
# Extract the temperature data
temperatures = df[3]
# Create a line plot of the temperature data
plt.plot(temperatures)
# Show the plot
plt.show()
此代码会将 CSV 文件中的数据读入 Pandas DataFrame,从第三列提取温度数据,并创建数据的线图。您可以根据需要通过添加轴标签、标题和其他详细信息来自定义绘图。
要创建其他类型的绘图,您可以使用具有不同 Matplotlib 或 Seaborn 函数的类似代码。例如,要创建天气数据的条形图,可以使用bar函数,要创建散点图,可以使用scatter函数。您还可以使用这些库来自定义绘图的外观并根据需要添加其他功能。