爬虫如果从重庆历年天气页面开始爬总是遇到2011年8月失败!

    1. """
    2. 重庆历史天气查询+气温可视化
    3. 每月天气数据获取 http://www.tianqihoubao.com/lishi/chongqing/month/202001.html
    4. 在每个月份页面种,天气情况是一个 table
    5. <table>
    6. <tr>
    7. <td>
    8. <b>日期</b>
    9. </td>
    10. <td>
    11. <b>天气状况</b>
    12. </td>
    13. <td>
    14. <b>气温</b>
    15. </td>
    16. <td>
    17. <b>风力风向</b>
    18. </td>
    19. </tr>
    20. <tr>
    21. <td>
    22. <a href="/lishi/chongqing/20210101.html" title="2021年01月01日重庆天气预报">2021年01月01日</a>
    23. </td>
    24. <td>多云 /多云</td>
    25. <td>10℃ / 4℃</td>
    26. <td>东北风 1-2级 /东北风 1-2级</td>
    27. </tr>
    28. 此处省略 n 天气温数据
    29. <tr>
    30. <td>
    31. <a href="/lishi/chongqing/20210131.html" title="2021年01月31日重庆天气预报">2021年01月31日</a>
    32. </td>
    33. <td>小雨 /小雨</td>
    34. <td>11℃ / 8℃</td>
    35. <td>西南风 1-2级 /西南风 1-2级</td>
    36. </tr>
    37. </tbody>
    38. 除表头tr标签外,其余tr标签包含每天天气情况
    39. 日期:<tr>下的第1个<td>下<a>标签文本
    40. 天气:<tr>下的第2个<td>标签
    41. 气温:<tr>下的第3个<td>标签
    42. 风向:<tr>下的第4个<td>标签
    43. 将所有数据存到一个 csv 文件中,格式为
    44. date weather temperature wind
    45. 2、数据可视化:创建日历型的气温热图
    46. """
    47. import requests
    48. from bs4 import BeautifulSoup
    49. from time import sleep, strptime
    50. import re
    51. import numpy as np
    52. import matplotlib.pyplot as plt
    53. plt.rcParams['font.sans-serif'] = ['SimHei'] # 设置字体为楷体
    54. def get_data(fileName):
    55. """获取重庆2020年天气"""
    56. headers1 = {
    57. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
    58. 'Accept-Encoding': 'gzip, deflate',
    59. 'Accept-Language': 'en',
    60. 'Host': 'www.tianqihoubao.com',
    61. 'Proxy-Connection': 'keep-alive',
    62. 'Upgrade-Insecure-Requests': '1',
    63. 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36',
    64. }
    65. with open(fileName, 'w', encoding='utf-8') as f:
    66. for i in range(1, 13):
    67. url = f'http://www.tianqihoubao.com/lishi/chongqing/month/2020{i:>02}.html'
    68. # 如果获取失败则再尝试2次获取
    69. ret = requests.get(url, headers=headers1)
    70. time = 1
    71. while time < 3 and ret.status_code != 200:
    72. time += 1
    73. print(f'{i}月天气获取失败,尝试第{time}次获取')
    74. sleep(2)
    75. ret = requests.get(url, headers=headers1)
    76. if ret.status_code == 200:
    77. soup = BeautifulSoup(ret.text, 'html.parser') # html解析
    78. trs = soup.select('table > tr')
    79. for j in range(1, len(trs)): # 每月天气
    80. line = []
    81. for td in trs[j].find_all('td'):
    82. line.append(''.join(td.get_text().split())) # 去除多余空白符
    83. print('\t'.join(line), file=f)
    84. print(f'{i:>02}月天气获取成功')
    85. else:
    86. print(f'{i:>02}月天气获取失败')
    87. sleep(1.5) # 每季度休眠1.5s
    88. print(f'爬取结束,数据保存在{fileName}文件中')
    89. get_data('2020年重庆天气数据.txt')
    90. def calendarHeatmap(day_nums, day_vals):
    91. """日历热图绘制函数:参考学习https://stackoverflow.com/a/61277350实现"""
    92. days = [ '日', '一', '二', '三', '四', '五', '六']
    93. months = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月']
    94. fig, ax = plt.subplots(3, 4, figsize=(14.85, 10.5))
    95. for i, axs in enumerate(ax.flat):
    96. axs.imshow(day_vals[i], cmap='hot_r', vmin=1, vmax=45) # heatmap
    97. axs.set_title(months[i])
    98. # Labels
    99. axs.set_xticks(np.arange(len(days))) # 设置刻度为7
    100. axs.set_xticklabels(days, fontsize=10, fontweight='bold', color='#555555') # 设置x轴标签
    101. axs.set_yticklabels([]) # 删除y轴标签
    102. axs.tick_params(axis=u'both', which=u'both', length=0) # 删除刻度mark
    103. axs.xaxis.tick_top() # 把x轴标签放在顶部(默认底部)
    104. # 修改标记位置以获得合适的网格位置
    105. axs.set_xticks(np.arange(-.5, 6, 1), minor=True)
    106. axs.set_yticks(np.arange(-.5, 5, 1), minor=True)
    107. axs.grid(which='minor', color='w', linestyle='-', linewidth=2.1)
    108. # 删除该grid边框
    109. for edge in ['left', 'right', 'bottom', 'top']:
    110. axs.spines[edge].set_color('#FFFFFF') # 换成白色
    111. # 注释,热图上标注具体问题
    112. for w in range(6):
    113. for d in range(7):
    114. day_val = day_vals[i][w, d]
    115. day_num = day_nums[i][w, d]
    116. if not np.isnan(day_val): # 非NaN才展示
    117. axs.text(d, w + 0.1, f"{day_val:0.0f}",
    118. ha="center", va="center",
    119. fontsize=15, color="b", alpha=0.5)
    120. fig.suptitle('2020年重庆平均气温热图', fontsize=30)
    121. plt.subplots_adjust(left=0.04, right=0.96, top=0.88, bottom=0.04) # 微调坐标
    122. plt.savefig('2020年重庆平均气温热图.jpg', dpi=600) # 保存
    123. plt.show() # 展示图片
    124. # 读取数据
    125. def readDate(fileName):
    126. """读取 fileName 内的数据,然后返回 12 个 6*7 的二维数组"""
    127. day_nums = [np.full((6, 7), np.nan) for _ in range(12)]
    128. day_vals = [np.full((6, 7), np.nan) for _ in range(12)]
    129. with open(fileName, encoding='utf-8') as f:
    130. lastMonth = -1
    131. for line in f:
    132. date, weather, temperature, wind = line.split('\t')
    133. high, low = map(int, re.findall(r'\d+', temperature))
    134. t = strptime(date, "%Y年%m月%d日") # 格式化为时间对象
    135. if t.tm_mon != lastMonth: # 下一个月
    136. idx = t.tm_wday # 当前日期是周几
    137. lastMonth = t.tm_mon
    138. r, c = divmod(idx, 7)
    139. day_nums[lastMonth-1][r][c] = t.tm_mday # 这个月第几天
    140. day_vals[lastMonth-1][r][c] = (high + low) / 2
    141. idx += 1
    142. return day_nums, day_vals
    143. calendarHeatmap(*readDate('2020年重庆天气数据.txt'))

    calendar_example.png