爬虫如果从重庆历年天气页面开始爬总是遇到2011年8月失败!
"""重庆历史天气查询+气温可视化每月天气数据获取 http://www.tianqihoubao.com/lishi/chongqing/month/202001.html在每个月份页面种,天气情况是一个 table<table><tr><td><b>日期</b></td><td><b>天气状况</b></td><td><b>气温</b></td><td><b>风力风向</b></td></tr><tr><td><a href="/lishi/chongqing/20210101.html" title="2021年01月01日重庆天气预报">2021年01月01日</a></td><td>多云 /多云</td><td>10℃ / 4℃</td><td>东北风 1-2级 /东北风 1-2级</td></tr>此处省略 n 天气温数据<tr><td><a href="/lishi/chongqing/20210131.html" title="2021年01月31日重庆天气预报">2021年01月31日</a></td><td>小雨 /小雨</td><td>11℃ / 8℃</td><td>西南风 1-2级 /西南风 1-2级</td></tr></tbody>除表头tr标签外,其余tr标签包含每天天气情况日期:<tr>下的第1个<td>下<a>标签文本天气:<tr>下的第2个<td>标签气温:<tr>下的第3个<td>标签风向:<tr>下的第4个<td>标签将所有数据存到一个 csv 文件中,格式为date weather temperature wind2、数据可视化:创建日历型的气温热图"""import requestsfrom bs4 import BeautifulSoupfrom time import sleep, strptimeimport reimport numpy as npimport matplotlib.pyplot as pltplt.rcParams['font.sans-serif'] = ['SimHei'] # 设置字体为楷体def get_data(fileName):"""获取重庆2020年天气"""headers1 = {'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','Accept-Encoding': 'gzip, deflate','Accept-Language': 'en','Host': 'www.tianqihoubao.com','Proxy-Connection': 'keep-alive','Upgrade-Insecure-Requests': '1','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',}with open(fileName, 'w', encoding='utf-8') as f:for i in range(1, 13):url = f'http://www.tianqihoubao.com/lishi/chongqing/month/2020{i:>02}.html'# 如果获取失败则再尝试2次获取ret = requests.get(url, headers=headers1)time = 1while time < 3 and ret.status_code != 200:time += 1print(f'{i}月天气获取失败,尝试第{time}次获取')sleep(2)ret = requests.get(url, headers=headers1)if ret.status_code == 200:soup = BeautifulSoup(ret.text, 'html.parser') # html解析trs = soup.select('table > tr')for j in range(1, len(trs)): # 每月天气line = []for td in trs[j].find_all('td'):line.append(''.join(td.get_text().split())) # 去除多余空白符print('\t'.join(line), file=f)print(f'{i:>02}月天气获取成功')else:print(f'{i:>02}月天气获取失败')sleep(1.5) # 每季度休眠1.5sprint(f'爬取结束,数据保存在{fileName}文件中')get_data('2020年重庆天气数据.txt')def calendarHeatmap(day_nums, day_vals):"""日历热图绘制函数:参考学习https://stackoverflow.com/a/61277350实现"""days = [ '日', '一', '二', '三', '四', '五', '六']months = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月']fig, ax = plt.subplots(3, 4, figsize=(14.85, 10.5))for i, axs in enumerate(ax.flat):axs.imshow(day_vals[i], cmap='hot_r', vmin=1, vmax=45) # heatmapaxs.set_title(months[i])# Labelsaxs.set_xticks(np.arange(len(days))) # 设置刻度为7axs.set_xticklabels(days, fontsize=10, fontweight='bold', color='#555555') # 设置x轴标签axs.set_yticklabels([]) # 删除y轴标签axs.tick_params(axis=u'both', which=u'both', length=0) # 删除刻度markaxs.xaxis.tick_top() # 把x轴标签放在顶部(默认底部)# 修改标记位置以获得合适的网格位置axs.set_xticks(np.arange(-.5, 6, 1), minor=True)axs.set_yticks(np.arange(-.5, 5, 1), minor=True)axs.grid(which='minor', color='w', linestyle='-', linewidth=2.1)# 删除该grid边框for edge in ['left', 'right', 'bottom', 'top']:axs.spines[edge].set_color('#FFFFFF') # 换成白色# 注释,热图上标注具体问题for w in range(6):for d in range(7):day_val = day_vals[i][w, d]day_num = day_nums[i][w, d]if not np.isnan(day_val): # 非NaN才展示axs.text(d, w + 0.1, f"{day_val:0.0f}",ha="center", va="center",fontsize=15, color="b", alpha=0.5)fig.suptitle('2020年重庆平均气温热图', fontsize=30)plt.subplots_adjust(left=0.04, right=0.96, top=0.88, bottom=0.04) # 微调坐标plt.savefig('2020年重庆平均气温热图.jpg', dpi=600) # 保存plt.show() # 展示图片# 读取数据def readDate(fileName):"""读取 fileName 内的数据,然后返回 12 个 6*7 的二维数组"""day_nums = [np.full((6, 7), np.nan) for _ in range(12)]day_vals = [np.full((6, 7), np.nan) for _ in range(12)]with open(fileName, encoding='utf-8') as f:lastMonth = -1for line in f:date, weather, temperature, wind = line.split('\t')high, low = map(int, re.findall(r'\d+', temperature))t = strptime(date, "%Y年%m月%d日") # 格式化为时间对象if t.tm_mon != lastMonth: # 下一个月idx = t.tm_wday # 当前日期是周几lastMonth = t.tm_monr, c = divmod(idx, 7)day_nums[lastMonth-1][r][c] = t.tm_mday # 这个月第几天day_vals[lastMonth-1][r][c] = (high + low) / 2idx += 1return day_nums, day_valscalendarHeatmap(*readDate('2020年重庆天气数据.txt'))

