Python中怎么爬取天气数据
发表于:2024-09-22 作者:千家信息网编辑
千家信息网最后更新 2024年09月22日,这期内容当中小编将会给大家带来有关Python中怎么爬取天气数据,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。使用pygal绘图,使用该模块前需先安装pip ins
千家信息网最后更新 2024年09月22日Python中怎么爬取天气数据使用pygal绘图,使用该模块前需先安装pip install pygal,然后导入import pygal
这期内容当中小编将会给大家带来有关Python中怎么爬取天气数据,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。
使用pygal绘图,使用该模块前需先安装pip install pygal,然后导入import pygal
bar = pygal.Line() # 创建折线图bar.add('最低气温', lows) #添加两线的数据序列bar.add('最高气温', highs) #注意lows和highs是int型的列表bar.x_labels = daytimesbar.x_labels_major = daytimes[::30]bar.x_label_rotation = 45bar.title = cityname+'未来七天气温走向图' #设置图形标题bar.x_title = '日期' #x轴标题bar.y_title = '气温(摄氏度)' # y轴标题bar.legend_at_bottom = Truebar.show_x_guides = Falsebar.show_y_guides = Truebar.render_to_file('temperate1.svg') # 将图像保存为SVG文件,可通过浏览器
完整代码
import csvimport sysimport urllib.requestfrom bs4 import BeautifulSoup # 解析页面模块import pygalimport cityinfocityname = input("请输入你想要查询天气的城市:")if cityname in cityinfo.city:citycode = cityinfo.city[cityname]else:sys.exit()url = '非常抱歉,网页无法访问' + citycode + '.shtml'header = ("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36") # 设置头部信息http_handler = urllib.request.HTTPHandler()opener = urllib.request.build_opener(http_handler) # 修改头部信息opener.addheaders = [header]request = urllib.request.Request(url) # 制作请求response = opener.open(request) # 得到应答包html = response.read() # 读取应答包html = html.decode('utf-8') # 设置编码,否则会乱码# 根据得到的页面信息进行初步筛选过滤final = [] # 初始化一个列表保存数据bs = BeautifulSoup(html, "html.parser") # 创建BeautifulSoup对象body = bs.bodydata = body.find('div', {'id': '7d'})print(type(data))ul = data.find('ul')li = ul.find_all('li')# 爬取自己需要的数据i = 0 # 控制爬取的天数lows = [] # 保存低温highs = [] # 保存高温daytimes = [] # 保存日期weathers = [] # 保存天气for day in li: # 便利找到的每一个liif i < 7:temp = [] # 临时存放每天的数据date = day.find('h2').string # 得到日期#print(date)temp.append(date)daytimes.append(date)inf = day.find_all('p') # 遍历li下面的p标签 有多个p需要使用find_all 而不是find#print(inf[0].string) # 提取第一个p标签的值,即天气temp.append(inf[0].string)weathers.append(inf[0].string)temlow = inf[1].find('i').string # 最低气温if inf[1].find('span') is None: # 天气预报可能没有最高气温temhigh = Nonetemperate = temlowelse:temhigh = inf[1].find('span').string # 最高气温temhigh = temhigh.replace('℃', '')temperate = temhigh + '/' + temlow# temp.append(temhigh)# temp.append(temlow)lowStr = ""lowStr = lowStr.join(temlow.string)lows.append(int(lowStr[:-1])) # 以上三行将低温NavigableString转成int类型并存入低温列表if temhigh is None:highs.append(int(lowStr[:-1]))highStr = ""highStr = highStr.join(temhigh)highs.append(int(highStr)) # 以上三行将高温NavigableString转成int类型并存入高温列表temp.append(temperate)final.append(temp)i = i + 1# 将最终的获取的天气写入csv文件with open('weather.csv', 'a', errors='ignore', newline='') as f:f_csv = csv.writer(f)f_csv.writerows([cityname])f_csv.writerows(final)# 绘图bar = pygal.Line() # 创建折线图bar.add('最低气温', lows)bar.add('最高气温', highs)bar.x_labels = daytimesbar.x_labels_major = daytimes[::30]# bar.show_minor_x_labels = False # 不显示X轴最小刻度bar.x_label_rotation = 45bar.title = cityname+'未来七天气温走向图'bar.x_title = '日期'bar.y_title = '气温(摄氏度)'bar.legend_at_bottom = Truebar.show_x_guides = Falsebar.show_y_guides = Truebar.render_to_file('temperate.svg')
Python爬取天气数据实例扩展:
import requestsfrom bs4 import BeautifulSoupfrom pyecharts import Bar ALL_DATA = []def send_parse_urls(start_urls):headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36"}for start_url in start_urls:response = requests.get(start_url,headers=headers)# 编码问题的解决response = response.text.encode("raw_unicode_escape").decode("utf-8")soup = BeautifulSoup(response,"html5lib") #lxml解析器:性能比较好,html5lib:适合页面结构比较混乱的div_tatall = soup.find("div",class_="conMidtab") #find() 找符合要求的第一个元素tables = div_tatall.find_all("table") #find_all() 找到符合要求的所有元素的列表for table in tables:trs = table.find_all("tr")info_trs = trs[2:]for index,info_tr in enumerate(info_trs): # 枚举函数,可以获得索引# print(index,info_tr)# print("="*30)city_td = info_tr.find_all("td")[0]temp_td = info_tr.find_all("td")[6]# if的判断的index的特殊情况应该在一般情况的后面,把之前的数据覆盖if index==0:city_td = info_tr.find_all("td")[1]temp_td = info_tr.find_all("td")[7]city=list(city_td.stripped_strings)[0]temp=list(temp_td.stripped_strings)[0]ALL_DATA.append({"city":city,"temp":temp})return ALL_DATA def get_start_urls():start_urls = ["http://www.weather.com.cn/textFC/hb.shtml","http://www.weather.com.cn/textFC/db.shtml","http://www.weather.com.cn/textFC/hd.shtml","http://www.weather.com.cn/textFC/hz.shtml","http://www.weather.com.cn/textFC/hn.shtml","http://www.weather.com.cn/textFC/xb.shtml","http://www.weather.com.cn/textFC/xn.shtml","http://www.weather.com.cn/textFC/gat.shtml",]return start_urls def main():"""主程序逻辑展示全国实时温度最低的十个城市气温排行榜的柱状图"""# 1 获取所有起始urlstart_urls = get_start_urls()# 2 发送请求获取响应、解析页面data = send_parse_urls(start_urls)# print(data)# 4 数据可视化#1排序data.sort(key=lambda data:int(data["temp"]))#2切片,选择出温度最低的十个城市和温度值show_data = data[:10]#3分出城市和温度city = list(map(lambda data:data["city"],show_data))temp = list(map(lambda data:int(data["temp"]),show_data))#4创建柱状图、生成目标图chart = Bar("中国最低气温排行榜") #需要安装pyechart模块chart.add("",city,temp)chart.render("tempture.html") if __name__ == '__main__':main()
上述就是小编为大家分享的Python中怎么爬取天气数据了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注行业资讯频道。
气温
天气
数据
最低
最高
城市
日期
温度
页面
低温
信息
标题
模块
高温
元素
内容
头部
情况
排行榜
文件
数据库的安全要保护哪些东西
数据库安全各自的含义是什么
生产安全数据库录入
数据库的安全性及管理
数据库安全策略包含哪些
海淀数据库安全审计系统
建立农村房屋安全信息数据库
易用的数据库客户端支持安全管理
连接数据库失败ssl安全错误
数据库的锁怎样保障安全
联通网络安全自查报告
微乐登陆说当前服务器繁忙
网络安全研究所
数据库 db2
根服务器的
中文科技期利数据库收录证书
数据库同步技术对比
公积金提取一直服务器异常
陕西小桔网络技术体检标准
苏州idc服务器如何连接电脑
数据库数据导出审批
一加手机语音助手连接不上服务器
怎样让数据库表里有相同的数据
lctf网络安全大赛
延庆区网络软件开发
我的世界服务器极限模式怎么关掉
forest如何进入大陆服务器
进入网站mysql数据库
网络安全等级保护ppt课件
高一课程计算机技术数据库
哈尔滨服务器租
58软件开发待遇
违反网络安全 有下列行为
公积金提取一直服务器异常
驻马店市政府网络安全
基金客户的档案数据库
赣州软件开发的平均工资
广州鲲鹏服务器
天津服务器搭建虚拟主机
查询选修课程学院人数数据库