首页 > 其他分享 >网络爬虫--爬取泉州,福州,厦门历史天气和近七日天气--数据可视化

网络爬虫--爬取泉州,福州,厦门历史天气和近七日天气--数据可视化

时间:2023-06-04 14:56:15浏览次数:41  
标签:city -- writer 天气 爬取 import csv data

 

一:选题背景:

通过爬取各个城市的历史天气数据及近日数据,来进行对天气的数据分析与可视化。从而帮助我们的生活更加便利。

所爬取的网站为2345天气王https://tianqi.2345.com/wea_forty/71924.htm

这里我们进入网站后右键检查,点击网络这一栏,并刷新页面能够看到有两个文件,而我们所需要的就是第二个文件里的地址。

随后我们讲这栏地址嵌入我们的代码中

import requests
import parsel
import csv
with open('泉州福州厦门历史天气.csv',mode='a',encoding='utf-8',newline='')as f:
csv_writer = csv.writer(f)
csv_writer.writerow(['日期','最高温度','最低温度','天气','风向','城市'])
city_list = [59131,58847,59134]
for city in city_list:
for year in range(2022, 2023):
for month in range(1,5):
url = f'https://tianqi.2345.com/Pc/GetHistory?areaInfo[areaId]={city}&areaInfo[areaType]=2&date[year]={year}&date[month]={month}'

response = requests.get(url=url)
select = parsel.Selector(response.json()['data'])
trs = select.css('table tr')
for tr in trs[1:]:
tds = tr.css('td::text').getall()
if city == 59131:
tds.append('泉州')
elif city == 58847:
tds.append('福州')
elif city == 59134:
tds.append('厦门')
print(tds)
with open('泉州福州厦门历史天气.csv', mode='a', encoding='utf-8', newline='') as f:
csv_writer = csv.writer(f)
csv_writer.writerow(tds) 这里是刚刚提取的地址:url = f'https://tianqi.2345.com/Pc/GetHistory?areaInfo[areaId]={city}&areaInfo[areaType]=2&date[year]={year}&date[month]={month}' 可以用图片中的来代替进行美化,这个代码我是用pycharm来运行的,需要注意缩进。不然就会报错。

第一行的数字就是代表着对应的城市,我这边截图的是丰泽区的。泉州的是59131。

这是采集的城市的代码:

采集城市天气数据的时间段:

对数据进行采集

用with open来保存数据,前面导入csv模块来写入我们的数据

随后我们就可以进行数据采集了。

采集后的效果如下

随后我们来到jupyter notebook。

先运行一遍我们的代码:

导入我们需要用到的模块:

import numpy as np
import pandas as pd
import time
import jieba
import datetime
from pyecharts import options as opts
from pyecharts.charts import *
from pyecharts.commons.utils import JsCode

用read来读取我们的数据:

可以看到有非常多条符合我们的内容。

data = pd.read_csv('泉州福州厦门历史天气.csv')

读入数据以后我们来进行数据预览:

用data.sample(5)来随机采样五个

将图表中多余的符号删除:

data[['最高温度','最低温度']] = data[['最高温度','最低温度']].apply(lambda x:x.str.replace('°',''))
data.head()

这里我采样的是不同的数据,所以与上面的内容不同。

同时我们也可以用代码来知道各个城市的下雨天数:

data.loc[data['天气'].str.contains('雨'),'下雨吗'] = '是'
data.fillna('否',inplace=True)

data.sample(5)

可以看到通过代码得出福州下雨天数最多

接下来就要进行最近七日的天气爬取,来分析未来的天气走势,直观表达内容。

我们将会用到三个地址:

厦门:http://www.weather.com.cn/weather/101230201.shtml
福州:http://www.weather.com.cn/weather/101230101.shtml
泉州:http://www.weather.com.cn/weather/101230501.shtm

我们把他们填入代码中

用requests来进行爬取代码

拿到天气的li,里面包含城市的数据:

创建数组,反便进一步用plot绘制折线图:

接下来对七天的li进行遍历,将数据存到数组中:

接下来是绘制折线图:

接下来展示不同网址后,运行的结果:

这张为泉州的近七日气温折线图:

这张是福州的近七日气温折现图:

这张是厦门的近七日气温折现图:

 

 

从这几张图可以看出所爬取的三个城市的气温变化图,直观明了。

以下是从头到尾的代码;

爬取2345天气网:


import requests

import parsel
import csv
with open('泉州福州厦门历史天气.csv',mode='a',encoding='utf-8',newline='')as f:
csv_writer = csv.writer(f)
csv_writer.writerow(['日期','最高温度','最低温度','天气','风向','城市'])
city_list = [59131,58847,59134]
for city in city_list:
for year in range(2022, 2023):
for month in range(1,5):
url = f'https://tianqi.2345.com/Pc/GetHistory?areaInfo[areaId]={city}&areaInfo[areaType]=2&date[year]={year}&date[month]={month}'

response = requests.get(url=url)
select = parsel.Selector(response.json()['data'])
trs = select.css('table tr')
for tr in trs[1:]:
tds = tr.css('td::text').getall()
if city == 59131:
tds.append('泉州')
elif city == 58847:
tds.append('福州')
elif city == 59134:
tds.append('厦门')
print(tds)
with open('泉州福州厦门历史天气.csv', mode='a', encoding='utf-8', newline='') as f:
csv_writer = csv.writer(f)
csv_writer.writerow(tds)

 

来到jupyter notebook。
import numpy as np
import pandas as pd
import time
import jieba
import datetime
from pyecharts import options as opts
from pyecharts.charts import *
from pyecharts.commons.utils import JsCode


data = pd.read_csv('泉州福州厦门历史天气.csv')


data.sample(5)
data.info()


data[['最高温度','最低温度']] = data[['最高温度','最低温度']].apply(lambda x:x.str.replace('°',''))
data.head()


data.loc[data['天气'].str.contains('雨'),'下雨吗'] = '是'
data.fillna('否',inplace=True)

data.sample(5)

 

爬取近七日天气数据折现图:


import requests
from lxml import etree
from pylab import *

 

# 设置爬取网站url
base_url = "http://www.weather.com.cn/weather/101230501.shtml"


# requests进行爬取代码
resp = requests.get(url=base_url)


# XPATH解析
html = etree.HTML(resp.text)


# 拿到天气的li,在li里包含每天天气的全部数据,包括日期/天气/气温/城市等等
lis = html.xpath('//*[@id="7d"]/ul/li')


# 创建日期、最高气温、最低气温的数组,为了后续把爬取的数据添加到数组中,进而进一步把数组用plot进行绘制折线图
days = []
lows = []
highs = []


# 对7天天气的li进行遍历,为了获取高低温度和日期
for li in lis:
print("正在爬取近7天···")
# 获取7天高温
high = li.xpath("./p[2]/span/text()")[0]
# 获取7天低温
low = li.xpath("./p[2]/i/text()")[0][0:2]
# 获取7天日期
day = li.xpath("./h1/text()")[0][0:2]
# 把7天日期、高温、低温添加到数组中
days.append(day)
lows.append((int)(low))
highs.append((int)(high))
# 设置休眠1秒
time.sleep(1)

print("日期列表如下:")
print(days)
print("最低气温列表如下:")
print(lows)
print("最高气温列表如下:")
print(highs)

# 下方代码绘制高低气温折线图图表
# 设置字体
mpl.rcParams['font.sans-serif'] = ['SimHei']
# 设置x轴长度
x = range(len(days))
# 限定纵轴的范围
plt.ylim(0, 40)
# 低温、高温数据加载,设置图形表示,设置解释
plt.plot(x, lows, marker='o', mec='r', mfc='w', label=u'最低气温')
plt.plot(x, highs, marker='*', ms=10, label=u'最高气温')
# 让图例生效
plt.legend()
plt.xticks(x, days, rotation=45)
plt.margins(0)
plt.subplots_adjust(bottom=0.15)
# X轴标签
plt.xlabel(u"日期")
# Y轴标签
plt.ylabel("温度")
# 标题
plt.title("近7日气温")
# 图例显示
plt.show()

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

标签:city,--,writer,天气,爬取,import,csv,data
From: https://www.cnblogs.com/211029zxy/p/17455667.html

相关文章

  • kubernetes部署nexus
    1.NexusVolumecat>nexus-volume.yaml<<EOF---apiVersion:v1kind:PersistentVolumeClaimmetadata:name:nexus-data-pvcnamespace:kube-opsspec:accessModes:-ReadWriteMany#指定storageClass的名字,这里使用默认的standardstorageClassName......
  • CAD 复制对象
    为了复制对象,要在对象上运用已提供的Clone函数。这个函数会创建一个与原始对象的重复的新对象。一旦创建了副本对象,就可以将其添加或附加到数据库之前对其进行修改。如果不变换对象或更改它们的位置,则新对象将位于与原对象相同的位置。如果你需要复制大量的对象,可以添加每个对象......
  • 小汽车练习
    drf管理员,用户,车,车厂,经销商接口实现1有车型(CarModel),车厂(CarFactory),经销商(Distributor)三个表,一个车厂可以生产多种车型,一个经销商可以出售多种车型,一个车型可以有多个经销商出售车型:车型名,车型出厂价,车厂id车厂:车厂名,车厂地址,联系电话经销商:经销商名,地址,联系电话2有......
  • vscode插件开发----在编辑栏上增加菜单项
    在package.json做如下配置:"contributes":{"commands":[{"command":"codeStat.countCurFile","title":"统计当前文件"}],"menus":{"editor/t......
  • 从日志记一次Spring事务完整流程
    spring事务一次完整流程,创建》确认获取连接》完成》提交》释放链接DataSourceTransactionManager//Step1.进入业务方法前,依据事物切面创建事务对象2019-07-0622:34:24,819[main]DEBUGo.s.j.d.DataSourceTransactionManager-Creatingnewtransactionwithname[com......
  • 比较有用的log4j.properties
    log4j.rootLogger=DEBUG,CONSOLE,DATABASE,FILElog4j.addivity.org.apache=true#应用于控制台log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppenderlog4j.appender.CONSOLE.Threshold=INFOlog4j.appender.CONSOLE.Target=System.outlog4j.appender.CONSOLE.Encoding=G......
  • 在Web里面用Jasper导出Pdf、HTML、Excel,以及参数说明
    参考:[color=red]ireport导出各种格式(pdf,excel,word,html,print)的例子[/color]:[url]http://mingxiao2010.blog.163.com/blog/static/861904812010665366872/[/url]说明:PDF:JRAbstractExporterexporter=newJRPdfExporter();Excel:JRAbstractExpor......
  • jQuery选择器大全(48个代码片段+21幅图演示)
    一、基本选择器1.id选择器(指定id元素)将id="one"的元素背景色设置为黑色。(id选择器返单个元素)$(document).ready(function(){$('#one').css('background','#000');});2.class选择器(遍历css类元素)将class="cube"的元素背景色设为黑色$(document).ready(......
  • JQuery Block UI V2
    [b][color=red]最好参考地址[/color][/b]:[url]http://www.cssrain.cn/demo/blockUI-V2/jQuery/blockUI/jQueryBlockUI.html[/url]ThejQueryBlockUI插件是用于进行AJAX操作时模拟同步传输时锁定浏览器操作[1]。当它被激活时,它会阻止使用者与页面(或页面的......
  • Eclipse的iBatis插件
    mybatiseditor[[color=red]EditorsupportforMyBatisandiBatisinEclipse[/color]][url]https://code.google.com/a/eclipselabs.org/p/mybatiseditor/[/url]InstallationYouuseoneofthefollowingmethodstoinstallMyBatisEditor:Ecl......