现在用xpath爬虫天气预报后进行可视化,要五十行代码
时间: 2024-03-15 19:43:04 浏览: 80
好的,以下是一个使用Python的Matplotlib和Seaborn库对爬取到的天气预报数据进行可视化的50行代码示例。
```python
import requests
from lxml import etree
import matplotlib.pyplot as plt
import seaborn as sns
# 爬取天气预报数据
url = 'https://tianqi.moji.com/weather/china/shanghai/pudong-new-district'
response = requests.get(url)
html = response.content.decode('utf-8')
tree = etree.HTML(html)
# 解析数据并存储到列表中
dates = tree.xpath('//div[@class="forecast clearfix"]/ul[@class="days clearfix"]/li/div[@class="wea"]/text()')
high_temps = tree.xpath('//div[@class="forecast clearfix"]/ul[@class="days clearfix"]/li/div[@class="tem"]/span/text()')
low_temps = tree.xpath('//div[@class="forecast clearfix"]/ul[@class="days clearfix"]/li/div[@class="tem"]/i/text()')
# 转换数据类型
high_temps = [int(t.replace('℃', '')) for t in high_temps]
low_temps = [int(t.replace('℃', '')) for t in low_temps]
# 创建一个柱状图
sns.set_style("whitegrid")
plt.figure(figsize=(8, 5))
plt.bar(dates, high_temps, alpha=0.7, width=0.4, label='High')
plt.bar(dates, low_temps, alpha=0.7, width=0.4, label='Low')
plt.legend(loc='upper right')
# 添加标题和标签
plt.title('Weather Forecast for Pudong New District, Shanghai')
plt.xlabel('Date')
plt.ylabel('Temperature (Celsius)')
# 显示图表
plt.show()
```
这段代码将爬取莫迪天气网站上上海市浦东新区的天气预报数据,并使用Matplotlib和Seaborn库创建一个柱状图来可视化数据。您可以根据需要修改图表类型和样式。
阅读全文