0


python爬虫——爬取全年天气数据并做可视化分析

在这里插入图片描述

一、主题页面的结构与特征分析

1.主题页面的结构与特征分析

目标内容界面:

2. Htmls 页面解析

3.节点查找方法与遍历方法

查找方法:find(): 查找第一个匹配到的节点。find_all(): 查找所有匹配到的节点,并返回一个列表。

遍历方法:contents: 返回当前节点的直接子节点列表。 children: 返回当前节点的直接子节点的迭代器。descendants: 返回当前节点的所有子孙节点的迭代器。

parent: 返回当前节点的父节点。parents: 返回当前节点的所有祖先节点的迭代器。

二、网络爬虫程序设计

1.数据爬取与采集

数据源:https://lishi.tianqi.com/quanzhou/

所用到的库有

  1. 1 import requests # 模拟浏览器进行网络请求
  2. 2 from lxml import etree # 进行数据预处理
  3. 3 import csv # 进行写入csv文件

使用requests中的get方法对网站发出请求,并接收响应数据,

1 resp = requests.get(url, headers=headers)

我们便得到了网页的源代码数据,

2.对数据进行清洗和处理

然后对爬取的网站源代码进行预处理

1 resp_html = etree.HTML(resp.text)

使用xpath工具提取我们所需要的数据

1 resp_list = resp_html.xpath(“//ul[@class=‘thrui’]/li”)

创建一个字典,并使用for循环将我们所提取的数据,放入字典中

  1. 1 for li in resp\_list: 2 day\_weather\_info = {} 3 # 日期
  2. 4 day\_weather\_info\['date\_time'\] = li.xpath("./div\[1\]/text()")\[0\].split(' ')\[0\]
  3. 5 # 最高气温 (包含摄氏度符号)
  4. 6 high = li.xpath("./div\[2\]/text()")\[0\]
  5. 7 day\_weather\_info\['high'\] = high\[:high.find('℃')\]
  6. 8 # 最低气温
  7. 9 low = li.xpath("./div\[3\]/text()")\[0\]
  8. 10 day\_weather\_info\['low'\] = low\[:low.find('℃')\]
  9. 11 # 天气
  10. 12 day\_weather\_info\['weather'\] = li.xpath("./div\[4\]/text()")\[0\]
  11. 13 weather\_info.append(day\_weather\_info)
  12. 14 return weather\_info

然后我们便得到了我们所需要的数据

接着爬取我们这个月的天气信息,存入列表中,然一次性写入我们的csv文件中,这样我们就得到了一个存有泉州2022全年天气情况的文件

  1. # for循环生成有顺序的1-12
  2. for month in range(1, 13):
  3. # 获取某一月的天气信息
  4. # 三元表达式
  5. weather\_time = '2022' + ('0' + str(month) if month < 10 else str(month))
  6. print(weather\_time)
  7. url \= f'https://lishi.tianqi.com/quanzhou/{weather\_time}.html'
  8. # 爬虫获取这个月的天气信息
  9. weather = getWeather(url)
  10. # 存到列表中
  11. weathers.append(weather)
  12. print(weathers)
  13. # 数据写入(一次性写入)
  14. with open("weather.csv", "w",newline='') as csvfile:
  15. writer \= csv.writer(csvfile)
  16. # 先写入列名:columns\_name 日期 最高气温 最低气温 天气
  17. writer.writerow(\["日期", "最高气温", "最低气温", '天气'\])
  18. # 一次写入多行用writerows(写入的数据类型是列表,一个列表对应一行)
  19. writer.writerows(\[list(day\_weather\_dict.values()) for month\_weather in weathers for day\_weather\_dict in month\_weather\])
  20. import sqlite3

文件如下:

3.对我们的数据进行一下词云处理

所用到的库

  1. 1 import requests
  2. 2 from lxml import etree
  3. 3 import csv
  4. 4 from wordcloud import WordCloud
  5. 5 import matplotlib.pyplot as plt

然后对数据在进行一次爬取与清理

  1. 1 # 从URL获取天气信息的函数
  2. 2 def getWeather(url): 3 weather\_info = \[\] # 存储天气信息的列表
  3. 4 headers = { 5 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.163 Safari/535.1'
  4. 6 }
  5. 7 resp = requests.get(url, headers=headers) # 发送GET请求到指定的URL
  6. 8 resp\_html = etree.HTML(resp.text) # 解析响应的HTML
  7. 9 resp\_list = resp\_html.xpath("//ul\[@class='thrui'\]/li") # 使用XPath选择器提取天气信息列表
  8. 10 for li in resp\_list:
  9. 11 day\_weather\_info = {} # 存储每天天气信息的字典
  10. 12 day\_weather\_info\['date\_time'\] = li.xpath("./div\[1\]/text()")\[0\].split(' ')\[0\] # 提取日期时间并存入字典
  11. 13 high = li.xpath("./div\[2\]/text()")\[0\] # 提取最高温度
  12. 14 day\_weather\_info\['high'\] = high\[:high.find('℃')\] # 去除温度单位并存入字典
  13. 15 low = li.xpath("./div\[3\]/text()")\[0\] # 提取最低温度
  14. 16 day\_weather\_info\['low'\] = low\[:low.find('℃')\] # 去除温度单位并存入字典
  15. 17 day\_weather\_info\['weather'\] = li.xpath("./div\[4\]/text()")\[0\] # 提取天气情况并存入字典
  16. 18 weather\_info.append(day\_weather\_info) # 将每天天气信息字典添加到天气信息列表中
  17. 19 return weather\_info
  18. 20 def main():
  19. 21 weathers = \[\] # 存储所有月份的天气信息的列表
  20. 22 for month in range(1, 13):
  21. 23 weather\_time = '2022' + ('0' + str(month) if month < 10 else str(month))
  22. 24 print(weather\_time)
  23. 25 url = f'https://lishi.tianqi.com/quanzhou/{weather\_time}.html'
  24. 26 weather = getWeather(url)
  25. 27 weathers.append(weather) # 将每个月份的天气信息添加到weathers列表中
  26. 28 print(weathers)
  27. 29
  28. 30 weather\_data = "" # 存储所有天气情况的字符串
  29. 31 for month\_weather in weathers:
  30. 32 for day\_weather\_dict in month\_weather:
  31. 33 weather = day\_weather\_dict\['weather'\] # 提取天气情况
  32. 34 weather\_data += weather + " " # 将天气情况添加到weather\_data字符串中,用空格分隔

然后便得到了我们熟悉的数据

wordcloud的分词可视化处理

  1. 1 wordcloud = WordCloud(font\_path='C:\\Windows\\Fonts\\微软雅黑\\msyh.ttc', width=800, height=400, font\_step=1,
  2. 2 prefer\_horizontal=0.9).generate(weather\_data) # 根据天气数据生成词云
  3. 3 plt.figure(figsize=(10, 5))
  4. 4 plt.imshow(wordcloud, interpolation='bilinear') # 显示词云图像
  5. 5 plt.axis('off')
  6. 6 plt.show()
  7. 7
  8. 8 if \_\_name\_\_ == '\_\_main\_\_':
  9. 9 main()

4.数据持久化

  1. import sqlite3
  2. def create\_weather\_table():
  3. conn \= sqlite3.connect('weather.db') # 连接到数据库文件
  4. cursor = conn.cursor()
  5. # 创建天气表格
  6. cursor.execute('''CREATE TABLE IF NOT EXISTS weather (
  7. date\_time TEXT,
  8. high TEXT,
  9. low TEXT,
  10. weather TEXT
  11. )''') # 创建天气表格,如果不存在则创建
  12. conn.commit() # 提交更改到数据库
  13. conn.close() # 关闭数据库连接
  14. def insert\_weather\_data(weather\_data):
  15. conn \= sqlite3.connect('weather.db') # 连接到数据库文件
  16. cursor = conn.cursor()
  17. # 插入天气数据
  18. for month\_weather in weather\_data:
  19. for day\_weather\_dict in month\_weather:
  20. date\_time \= day\_weather\_dict\['date\_time'\] # 获取日期时间
  21. high = day\_weather\_dict\['high'\] # 获取最高温度
  22. low = day\_weather\_dict\['low'\] # 获取最低温度
  23. weather = day\_weather\_dict\['weather'\] # 获取天气情况
  24. cursor.execute("INSERT INTO weather VALUES (?, ?, ?, ?)", (date\_time, high, low, weather)) # 插入数据到天气表格
  25. conn.commit() # 提交更改到数据库
  26. conn.close() # 关闭数据库连接
  27. def main():
  28. create\_weather\_table() # 创建天气表格
  29. weathers \= \[\] # 存储所有月份的天气信息的列表
  30. for month in range(1, 13):
  31. weather\_time \= '2022' + ('0' + str(month) if month < 10 else str(month))
  32. print(weather\_time)
  33. url \= f'https://lishi.tianqi.com/quanzhou/{weather\_time}.html'
  34. weather \= getWeather(url) # 获取天气信息
  35. weathers.append(weather)
  36. print(weathers)
  37. insert\_weather\_data(weathers)
  38. if \_\_name\_\_ == '\_\_main\_\_':
  39. main()

然后数据便以库文件的方式存入电脑中

5.数据可视化

所用到的库

  1. 1 import pandas as pd
  2. 2 from pyecharts import options as opts
  3. 3 from pyecharts.charts import Pie, Bar, Timeline, Line, Scatter

使用pandas.read_csv()读取我们数据文件

1 df = pd.read_csv(‘weather.csv’,encoding=‘gb18030’)

因为绘制的图形是动态的天气轮播图,而此时我们日期的数据类型为字符串,要将类型改为datetime

1 df[‘日期’] = df[‘日期’].apply(lambda x: pd.to_datetime(x))

使用GroupBy聚合对象 以及size().reset_index()方法来将每种天气出现的次数等数据进行分组,统计。

  1. 1 df\_agg = df.groupby(\['month','天气'\]).size().reset\_index()
  2. 2 print(df\_agg)

对每列数据进行一个命名

  1. df\_agg.columns = \['month','tianqi','count'\]
  2. print(df\_agg)

将数据转化为列表数据

  1. 1 print(df\_agg\[df\_agg\['month'\]==1\]\[\['tianqi','count'\]\]\\
  2. 2 .sort\_values(by='count',ascending=False).values.tolist())

将处理好的数据传入图表中,绘制横放柱状轮播图

  1. 1 # 画图
  2. 2 # 实例化一个时间序列的对象
  3. 3 timeline = Timeline() 4 # 播放参数:设置时间间隔 1s 单位是:ms(毫秒)
  4. 5 timeline.add\_schema(play\_interval=1000) # 单位是:ms(毫秒)
  5. 6
  6. 7 # 循环遍历df\_agg\['month'\]里的唯一值
  7. 8 for month in df\_agg\['month'\].unique():
  8. 9 data = (
  9. 10
  10. 11 df\_agg\[df\_agg\['month'\]==month\]\[\['tianqi','count'\]\]
  11. 12 .sort\_values(by='count',ascending=True)
  12. 13 .values.tolist()
  13. 14 )
  14. 15 # print(data)
  15. 16 # 绘制柱状图
  16. 17 bar = Bar()
  17. 18 # x轴是天气名称
  18. 19 bar.add\_xaxis(\[x\[0\] for x in data\])
  19. 20 # y轴是出现次数
  20. 21 bar.add\_yaxis('',\[x\[1\] for x in data\])
  21. 22
  22. 23 # 让柱状图横着放
  23. 24 bar.reversal\_axis()
  24. 25 # 将计数标签放置在图形右边
  25. 26 bar.set\_series\_opts(label\_opts=opts.LabelOpts(position='right'))
  26. 27 # 设置下图表的名称
  27. 28 bar.set\_global\_opts(title\_opts=opts.TitleOpts(title='泉州2022年每月天气变化 '))
  28. 29 # 将设置好的bar对象放置到时间轮播图当中,并且标签选择月份 格式为: 数字月
  29. 30 timeline.add(bar, f'{month}月')
  30. 31
  31. 32 # 将设置好的图表保存为'weathers.html'文件
  32. 33 timeline.render('weathers1.html')

#由于视频上传不了,所以只放了两个月份的天气数据图片

绘制折线图

  1. 1 # 画图
  2. 2 # 实例化一个时间序列的对象
  3. 3 timeline = Timeline() 4 # 播放参数:设置时间间隔 1s 单位是:ms(毫秒)
  4. 5 timeline.add\_schema(play\_interval=1000) # 单位是:ms(毫秒)
  5. 6
  6. 7 # 循环遍历df\_agg\['tianqi'\]里的唯一值(天气类型)
  7. 8 for tianqi in df\_agg\['tianqi'\].unique():
  8. 9 data = (
  9. 10 df\_agg\[df\_agg\['tianqi'\] == tianqi\]\[\['month', 'count'\]\]
  10. 11 .sort\_values(by='month', ascending=True)
  11. 12 .values.tolist()
  12. 13 )
  13. 14 # print(data)
  14. 15 # 绘制折线图
  15. 16 line = Line()
  16. 17 # x轴是月份
  17. 18 line.add\_xaxis(\[x\[0\] for x in data\])
  18. 19 # y轴是出现次数
  19. 20 line.add\_yaxis(tianqi, \[x\[1\] for x in data\], is\_smooth=True)
  20. 21
  21. 22 # 设置图线平滑曲线
  22. 23 line.set\_series\_opts(
  23. 24 markpoint\_opts=opts.MarkPointOpts(
  24. 25 data=\[opts.MarkPointItem(type\_="max", name="最大值")\]
  25. 26 )
  26. 27 )
  27. 28
  28. 29 # 设置下图表的名称
  29. 30 line.set\_global\_opts(
  30. 31 title\_opts=opts.TitleOpts(title='泉州2022年天气趋势'),
  31. 32 datazoom\_opts=opts.DataZoomOpts(type\_="slider", range\_start=0, range\_end=100),
  32. 33 )
  33. 34
  34. 35 # 将设置好的line对象放置到时间轮播图中,并且标签选择天气类型
  35. 36 timeline.add(line, tianqi)
  36. 37
  37. 38 # 将设置好的时间轮播图渲染为HTML文件
  38. 39 timeline.render("weather\_trend.html")

绘制散点图

  1. 1 # 画图
  2. 2 # 实例化一个散点图对象
  3. 3 scatter = Scatter() 4 # 播放参数:设置时间间隔 1s 单位是:ms(毫秒)
  4. 5 timeline.add\_schema(play\_interval=1000) # 单位是:ms(毫秒)
  5. 6
  6. 7 # 循环遍历df\_agg\['month'\]里的唯一值
  7. 8 for month in df\_agg\['month'\].unique():
  8. 9 data = (
  9. 10 df\_agg\[df\_agg\['month'\]==month\]\[\['tianqi','count'\]\]
  10. 11 .sort\_values(by='count',ascending=True)
  11. 12 .values.tolist()
  12. 13 )
  13. 14 # 绘制散点图
  14. 15 scatter = Scatter()
  15. 16 # x轴是天气名称
  16. 17 scatter.add\_xaxis(\[x\[0\] for x in data\])
  17. 18 # y轴是出现次数
  18. 19 scatter.add\_yaxis('',\[x\[1\] for x in data\])
  19. 20
  20. 21 # 设置下图表的名称
  21. 22 scatter.set\_global\_opts(title\_opts=opts.TitleOpts(title=f'{month}月天气散点图'))
  22. 23
  23. 24 # 将设置好的scatter对象放置到时间轮播图当中,并且标签选择月份 格式为: 数字月
  24. 25 timeline.add(scatter, f'{month}月')
  25. 26
  26. 27 # 将设置好的时间轮播图渲染为html文件
  27. 28 timeline.render('scatter\_timeline.html')

根据以上几个可视化图形可知

泉州市的降雨集中在5月至9月期间,而晴天比较多的月份是10月至来年3月。

6.将以上各部分的代码汇总,附上完整程序代码

(1)数据爬取与清洗,以及持久化部分

  1. 1 #\-\*- coding: utf-8 -\*-
  2. 2 import requests # 模拟浏览器进行网络请求
  3. 3 from lxml import etree # 进行数据预处理
  4. 4 import csv # 写入csv文件
  5. 5 import sqlite3 6 def getWeather(url): 7 weather\_info = \[\] # 新建一个列表,将爬取的每月数据放进去
  6. 8 # 请求头信息:浏览器版本型号,接收数据的编码格式
  7. 9 headers = { 10 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.163 Safari/535.1'
  8. 11 }
  9. 12 # 请求 接收到了响应数据
  10. 13 resp = requests.get(url, headers=headers)
  11. 14 # 数据预处理s
  12. 15 resp\_html = etree.HTML(resp.text) 16 # xpath提取所有数据
  13. 17 resp\_list = resp\_html.xpath("//ul\[@class='thrui'\]/li")
  14. 18 # for循环迭代遍历
  15. 19 for li in resp\_list: 20 day\_weather\_info = {} 21 # 日期
  16. 22 day\_weather\_info\['date\_time'\] = li.xpath("./div\[1\]/text()")\[0\].split(' ')\[0\]
  17. 23 # 最高气温 (包含摄氏度符号)
  18. 24 high = li.xpath("./div\[2\]/text()")\[0\]
  19. 25 day\_weather\_info\['high'\] = high\[:high.find('℃')\]
  20. 26 # 最低气温
  21. 27 low = li.xpath("./div\[3\]/text()")\[0\]
  22. 28 day\_weather\_info\['low'\] = low\[:low.find('℃')\]
  23. 29 # 天气
  24. 30 day\_weather\_info\['weather'\] = li.xpath("./div\[4\]/text()")\[0\]
  25. 31 weather\_info.append(day\_weather\_info)
  26. 32 return weather\_info 33
  27. 34 weathers = \[\] 35
  28. 36 # for循环生成有顺序的1-12
  29. 37 for month in range(1, 13):
  30. 38 # 获取某一月的天气信息
  31. 39 # 三元表达式
  32. 40 weather\_time = '2022' + ('0' + str(month) if month < 10 else str(month)) 41 print(weather\_time)
  33. 42 url = f'https://lishi.tianqi.com/quanzhou/{weather\_time}.html'
  34. 43 # 爬虫获取这个月的天气信息
  35. 44 weather = getWeather(url) 45 # 存到列表中
  36. 46 weathers.append(weather)
  37. 47 print(weathers)
  38. 48
  39. 49
  40. 50 # 数据写入(一次性写入)
  41. 51 with open("weather.csv", "w",newline='') as csvfile:
  42. 52 writer = csv.writer(csvfile) 53 # 先写入列名:columns\_name 日期 最高气温 最低气温 天气
  43. 54 writer.writerow(\["日期", "最高气温", "最低气温", '天气'\])
  44. 55 # 一次写入多行用writerows(写入的数据类型是列表,一个列表对应一行)
  45. 56 writer.writerows(\[list(day\_weather\_dict.values()) for month\_weather in weathers for day\_weather\_dict in month\_weather\]) 57
  46. 58
  47. 59 import sqlite3 60
  48. 61
  49. 62 def create\_weather\_table(): 63 conn = sqlite3.connect('weather.db') # 连接到数据库文件
  50. 64 cursor = conn.cursor() 65
  51. 66 # 创建天气表格
  52. 67 cursor.execute('''CREATE TABLE IF NOT EXISTS weather (
  53. 68 date\_time TEXT,
  54. 69 high TEXT,
  55. 70 low TEXT,
  56. 71 weather TEXT
  57. 72 )''') # 创建天气表格,如果不存在则创建
  58. 73
  59. 74 conn.commit() # 提交更改到数据库
  60. 75 conn.close() # 关闭数据库连接
  61. 76
  62. 77
  63. 78 def insert\_weather\_data(weather\_data): 79 conn = sqlite3.connect('weather.db') # 连接到数据库文件
  64. 80 cursor = conn.cursor() 81
  65. 82 # 插入天气数据
  66. 83 for month\_weather in weather\_data: 84 for day\_weather\_dict in month\_weather: 85 date\_time = day\_weather\_dict\['date\_time'\] # 获取日期时间
  67. 86 high = day\_weather\_dict\['high'\] # 获取最高温度
  68. 87 low = day\_weather\_dict\['low'\] # 获取最低温度
  69. 88 weather = day\_weather\_dict\['weather'\] # 获取天气情况
  70. 89
  71. 90 cursor.execute("INSERT INTO weather VALUES (?, ?, ?, ?)", (date\_time, high, low, weather)) # 插入数据到天气表格
  72. 91
  73. 92 conn.commit() # 提交更改到数据库
  74. 93 conn.close() # 关闭数据库连接
  75. 94
  76. 95
  77. 96 def main(): 97 create\_weather\_table() # 创建天气表格
  78. 98
  79. 99 weathers = \[\] # 存储所有月份的天气信息的列表
  80. 100 for month in range(1, 13):
  81. 101 weather\_time = '2022' + ('0' + str(month) if month < 10 else str(month))
  82. 102 print(weather\_time)
  83. 103 url = f'https://lishi.tianqi.com/quanzhou/{weather\_time}.html'
  84. 104 weather = getWeather(url) # 获取天气信息
  85. 105
  86. 106
  87. 107 weathers.append(weather)
  88. 108 print(weathers)
  89. 109
  90. 110 insert\_weather\_data(weathers)
  91. 111
  92. 112 if \_\_name\_\_ == '\_\_main\_\_':
  93. 113 main()

(2)数据可视化部分

  1. 1 #\-\*- coding: utf-8 -\*-
  2. 2
  3. 3 # 数据分析 读取 处理 存储
  4. 4 import pandas as pd 5 from pyecharts import options as opts 6 from pyecharts.charts import Pie, Bar, Timeline, Line, Scatter 7
  5. 8 # 用pandas.read\_csv()读取指定的excel文件,选择编码格式gb18030(gb18030范围比)
  6. 9 df = pd.read\_csv('weather.csv',encoding='gb18030')
  7. 10 print(df\['日期'\])
  8. 11
  9. 12 # 将日期格式的数据类型改为month
  10. 13 df\['日期'\] = df\['日期'\].apply(lambda x: pd.to\_datetime(x)) 14 print(df\['日期'\])
  11. 15
  12. 16
  13. 17 # 新建一列月份数据(将日期中的月份month 一项单独拿取出来)
  14. 18 df\['month'\] = df\['日期'\].dt.month
  15. 19
  16. 20 print(df\['month'\])
  17. 21 # 需要的数据 每个月中每种天气出现的次数
  18. 22
  19. 23 # DataFrame GroupBy聚合对象 分组和统计的 size()能够计算分组的大小
  20. 24 df\_agg = df.groupby(\['month','天气'\]).size().reset\_index()
  21. 25 print(df\_agg)
  22. 26
  23. 27 # 设置下这3列的列名
  24. 28 df\_agg.columns = \['month','tianqi','count'\]
  25. 29 print(df\_agg)
  26. 30
  27. 31 # 转化为列表数据
  28. 32 print(df\_agg\[df\_agg\['month'\]==1\]\[\['tianqi','count'\]\]\\
  29. 33 .sort\_values(by='count',ascending=False).values.tolist())
  30. 34 """
  31. 35 \[\['阴', 20\], \['多云', 5\], \['雨夹雪', 4\], \['晴', 2\]\]
  32. 36 """
  33. 37
  34. 38 # 画图
  35. 39 # 实例化一个时间序列的对象
  36. 40 timeline = Timeline() 41 # 播放参数:设置时间间隔 1s 单位是:ms(毫秒)
  37. 42 timeline.add\_schema(play\_interval=1000) # 单位是:ms(毫秒)
  38. 43
  39. 44 # 循环遍历df\_agg\['month'\]里的唯一值
  40. 45 for month in df\_agg\['month'\].unique():
  41. 46 data = ( 47
  42. 48 df\_agg\[df\_agg\['month'\]==month\]\[\['tianqi','count'\]\]
  43. 49 .sort\_values(by='count',ascending=True)
  44. 50 .values.tolist()
  45. 51 )
  46. 52 # print(data)
  47. 53 # 绘制柱状图
  48. 54 bar = Bar() 55 # x轴是天气名称
  49. 56 bar.add\_xaxis(\[x\[0\] for x in data\]) 57 # y轴是出现次数
  50. 58 bar.add\_yaxis('',\[x\[1\] for x in data\]) 59
  51. 60 # 让柱状图横着放
  52. 61 bar.reversal\_axis()
  53. 62 # 将计数标签放置在图形右边
  54. 63 bar.set\_series\_opts(label\_opts=opts.LabelOpts(position='right'))
  55. 64 # 设置下图表的名称
  56. 65 bar.set\_global\_opts(title\_opts=opts.TitleOpts(title='泉州2022年每月天气变化 '))
  57. 66 # 将设置好的bar对象放置到时间轮播图当中,并且标签选择月份 格式为: 数字月
  58. 67 timeline.add(bar, f'{month}月')
  59. 68
  60. 69 # 将设置好的图表保存为'weathers.html'文件
  61. 70 timeline.render('weathers1.html')
  62. 71
  63. 72
  64. 73 # 画图
  65. 74 # 实例化一个时间序列的对象
  66. 75 timeline = Timeline() 76 # 播放参数:设置时间间隔 1s 单位是:ms(毫秒)
  67. 77 timeline.add\_schema(play\_interval=1000) # 单位是:ms(毫秒)
  68. 78
  69. 79 # 循环遍历df\_agg\['tianqi'\]里的唯一值(天气类型)
  70. 80 for tianqi in df\_agg\['tianqi'\].unique():
  71. 81 data = ( 82 df\_agg\[df\_agg\['tianqi'\] == tianqi\]\[\['month', 'count'\]\]
  72. 83 .sort\_values(by='month', ascending=True)
  73. 84 .values.tolist()
  74. 85 )
  75. 86 # print(data)
  76. 87 # 绘制折线图
  77. 88 line = Line() 89 # x轴是月份
  78. 90 line.add\_xaxis(\[x\[0\] for x in data\]) 91 # y轴是出现次数
  79. 92 line.add\_yaxis(tianqi, \[x\[1\] for x in data\], is\_smooth=True)
  80. 93
  81. 94 # 设置图线平滑曲线
  82. 95 line.set\_series\_opts(
  83. 96 markpoint\_opts=opts.MarkPointOpts(
  84. 97 data=\[opts.MarkPointItem(type\_="max", name="最大值")\]
  85. 98 )
  86. 99 )
  87. 100
  88. 101 # 设置下图表的名称
  89. 102 line.set\_global\_opts(
  90. 103 title\_opts=opts.TitleOpts(title='泉州2022年天气趋势'),
  91. 104 datazoom\_opts=opts.DataZoomOpts(type\_="slider", range\_start=0, range\_end=100),
  92. 105 )
  93. 106
  94. 107 # 将设置好的line对象放置到时间轮播图中,并且标签选择天气类型
  95. 108 timeline.add(line, tianqi)
  96. 109
  97. 110 # 将设置好的时间轮播图渲染为HTML文件
  98. 111 timeline.render("weather\_trend.html")
  99. 112
  100. 113 # 画图
  101. 114 # 实例化一个散点图对象
  102. 115 scatter = Scatter()
  103. 116 # 播放参数:设置时间间隔 1s 单位是:ms(毫秒)
  104. 117 timeline.add\_schema(play\_interval=1000) # 单位是:ms(毫秒)
  105. 118
  106. 119 # 循环遍历df\_agg\['month'\]里的唯一值
  107. 120 for month in df\_agg\['month'\].unique():
  108. 121 data = (
  109. 122 df\_agg\[df\_agg\['month'\]==month\]\[\['tianqi','count'\]\]
  110. 123 .sort\_values(by='count',ascending=True)
  111. 124 .values.tolist()
  112. 125 )
  113. 126 # 绘制散点图
  114. 127 scatter = Scatter()
  115. 128 # x轴是天气名称
  116. 129 scatter.add\_xaxis(\[x\[0\] for x in data\])
  117. 130 # y轴是出现次数
  118. 131 scatter.add\_yaxis('',\[x\[1\] for x in data\])
  119. 132
  120. 133 # 设置下图表的名称
  121. 134 scatter.set\_global\_opts(title\_opts=opts.TitleOpts(title=f'{month}月天气散点图'))
  122. 135
  123. 136 # 将设置好的scatter对象放置到时间轮播图当中,并且标签选择月份 格式为: 数字月
  124. 137 timeline.add(scatter, f'{month}月')
  125. 138
  126. 139 # 将设置好的时间轮播图渲染为html文件
  127. 140 timeline.render('scatter\_timeline.html')
  128. 141 import numpy as np
  129. 142 from sklearn.linear\_model import LinearRegression

(3)wordcloud分词可视化,词云部分

  1. 1 1 # -\*- coding: utf-8 -\*-
  2. 2 2
  3. 3 3 # 导入必要的库
  4. 4 4 import requests 5 5 from lxml import etree 6 6 import csv 7 7 from wordcloud import WordCloud 8 8 import matplotlib.pyplot as plt 9 9
  5. 10 10 # 从URL获取天气信息的函数s
  6. 11 11 def getWeather(url):
  7. 12 12 weather\_info = \[\] # 存储天气信息的列表
  8. 13 13 headers = {
  9. 14 14 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.163 Safari/535.1'
  10. 15 15 }
  11. 16 16 resp = requests.get(url, headers=headers) # 发送GET请求到指定的URL
  12. 17 17 resp\_html = etree.HTML(resp.text) # 解析响应的HTML
  13. 18 18 resp\_list = resp\_html.xpath("//ul\[@class='thrui'\]/li") # 使用XPath选择器提取天气信息列表
  14. 19 19 for li in resp\_list:
  15. 20 20 day\_weather\_info = {} # 存储每天天气信息的字典
  16. 21 21 day\_weather\_info\['date\_time'\] = li.xpath("./div\[1\]/text()")\[0\].split(' ')\[0\] # 提取日期时间并存入字典
  17. 22 22 high = li.xpath("./div\[2\]/text()")\[0\] # 提取最高温度
  18. 23 23 day\_weather\_info\['high'\] = high\[:high.find('℃')\] # 去除温度单位并存入字典
  19. 24 24 low = li.xpath("./div\[3\]/text()")\[0\] # 提取最低温度
  20. 25 25 day\_weather\_info\['low'\] = low\[:low.find('℃')\] # 去除温度单位并存入字典
  21. 26 26 day\_weather\_info\['weather'\] = li.xpath("./div\[4\]/text()")\[0\] # 提取天气情况并存入字典
  22. 27 27 weather\_info.append(day\_weather\_info) # 将每天天气信息字典添加到天气信息列表中
  23. 28 28 return weather\_info
  24. 29 29 def main():
  25. 30 30 weathers = \[\] # 存储所有月份的天气信息的列表
  26. 31 31 for month in range(1, 13):
  27. 32 32 weather\_time = '2022' + ('0' + str(month) if month < 10 else str(month))
  28. 33 33 print(weather\_time)
  29. 34 34 url = f'https://lishi.tianqi.com/quanzhou/{weather\_time}.html'
  30. 35 35 weather = getWeather(url)
  31. 36 36 weathers.append(weather) # 将每个月份的天气信息添加到weathers列表中
  32. 37 37 print(weathers)
  33. 38 38
  34. 39 39 weather\_data = "" # 存储所有天气情况的字符串
  35. 40 40 for month\_weather in weathers:
  36. 41 41 for day\_weather\_dict in month\_weather:
  37. 42 42 weather = day\_weather\_dict\['weather'\] # 提取天气情况
  38. 43 43 weather\_data += weather + " " # 将天气情况添加到weather\_data字符串中,用空格分隔
  39. 44 44
  40. 45 45 wordcloud = WordCloud(font\_path='C:\\Windows\\Fonts\\微软雅黑\\msyh.ttc', width=800, height=400, font\_step=1,
  41. 46 46 prefer\_horizontal=0.9).generate(weather\_data) # 根据天气数据生成词云
  42. 47 47 plt.figure(figsize=(10, 5))
  43. 48 48 plt.imshow(wordcloud, interpolation='bilinear') # 显示词云图像
  44. 49 49 plt.axis('off')
  45. 50 50 plt.show()
  46. 51 51
  47. 52 52 if \_\_name\_\_ == '\_\_main\_\_':
  48. 53 53 main()

在这里插入图片描述


本文转载自: https://blog.csdn.net/m0_62283350/article/details/140295452
版权归原作者 进击的六角龙 所有, 如有侵权,请联系我们删除。

“python爬虫——爬取全年天气数据并做可视化分析”的评论:

还没有评论