写一个爬取泉州最近七天的天气预报、链接地址,天气类型,温度、风力、风向等数据并存储在mysql数据库中的天气预报表中
时间: 2024-10-06 11:01:17 浏览: 87
在Python中,你可以使用requests库来抓取网页数据,BeautifulSoup库解析HTML,然后利用正则表达式提取你需要的信息。对于天气预报,通常需要访问某个天气API或者网站的公开数据接口。例如,中国气象局的API或者第三方如“知了天气”提供的API可能会提供这样的信息。
以下是一个简单的示例,假设我们有一个模拟的API返回的数据结构:
```python
import requests
from bs4 import BeautifulSoup
import re
import pymysql
# 假设这是一个获取天气的API URL
weather_api_url = "http://example.com/weather/qz/7days"
response = requests.get(weather_api_url)
soup = BeautifulSoup(response.text, 'html.parser')
# 提取数据部分,这将依赖于实际API的响应结构
data = soup.find_all('div', class_='weather-item') # 这里只是个假设,实际情况需替换
# 创建连接到MySQL数据库
db = pymysql.connect(host="localhost", user="your_username", password="your_password", db="weather_forecast")
cursor = db.cursor()
# SQL插入模板
insert_sql = """
INSERT INTO weather_report (
link,
date,
type,
temperature,
wind_power,
wind_direction
) VALUES (%s, %s, %s, %s, %s, %s)
"""
for item in data:
try:
link = item.find('a')['href']
date_str = item.find('span', class_='date').text
type_str = item.find('span', class_='type').text
temp_str = item.find('span', class_='temperature').text
wind_power_str = item.find('span', class_='wind-power').text
wind_dir_str = item.find('span', class_='wind-direction').text
# 根据API返回的实际数据类型调整提取
date = datetime.strptime(date_str, '%Y-%m-%d')
temp = int(re.search(r'\d+', temp_str).group()) # 示例,实际可能是float或其他处理方式
wind_power = int(re.search(r'\d+', wind_power_str).group())
wind_direction = wind_dir_str.strip() # 清理字符串
cursor.execute(insert_sql, (link, date, type_str, temp, wind_power, wind_direction))
except Exception as e:
print(f"Error extracting data: {e}")
db.commit()
cursor.close()
db.close()
阅读全文
相关推荐

















