【python】爬取中国天气网中泉州一周的天气并保存到表格中


前言

今天来实现一下用pycharm工具写一份关于爬取中国天气网中泉州一周的天气并保存到表格中的文章

该文章主要是在中国天气网中爬取相应的天气信息,我以泉州为例,爬取泉州一周的天气信息包含当日的最低气温和最高气温,并将其保存在表格中,该实验是数据采集实验中要掌握的部分,涉及到如何爬取,如何请求,设置请求头等等知识点,那话不多说,我们开始吧~


一、实验具备的条件

  1. 有要爬取的url或者说是要爬取的网站地址
  2. 要知道如何设置请求头
  3. 要掌握如何将数据保存到本地的文件中

二、实验步骤

1.引入库

如果在导入相应的包的时候出现红色波浪线,要么就是没有安装相应的包,要先安装包才能不报错;要么就是代码有相应的问题要进行检查,库可以后面用到的时候想到一些再进行补充

import requests
import csv
import random
import time
import socket
import http.client
# import urllib.request
from bs4 import BeautifulSoup

2.查看中国天气网中泉州天气的源码

第一步:进入网站右键空白处,点击检查
在这里插入图片描述
第二步:点击网络,再ctrl+R刷新页面,找到要爬取的地址(第一个),点击标头,按网页设置请求头
在这里插入图片描述
按下面代码这样设置,例如:

def get_content(url, data=None):
    header = {
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
        'Cache-Control': "max-age=0",
        'Connection': 'keep-alive',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36 Edg/111.0.1661.51'
    }

:如果要爬取其他城市的天气也按此方法,将要爬取网站中的请求头找到,然后更换即可

3.将最低气温和最高气温找到并保存到本地

:通用的代码,即使换其他城市且实验要求一样,都无需更改该段代码

    timeout = random.choice(range(80, 180))
    while True:
        try:
            rep = requests.get(url, headers=header, timeout=timeout)
            rep.encoding = 'utf-8'
            break
        except socket.timeout as e:
            print('3:', e)
            time.sleep(random.choice(range(8, 15)))

        except socket.error as e:
            print('4:', e)
            time.sleep(random.choice(range(20, 60)))

        except http.client.BadStatusLine as e:
            print('5:', e)
            time.sleep(random.choice(range(30, 80)))

        except http.client.IncompleteRead as e:
            print('6:', e)
            time.sleep(random.choice(range(5, 15)))

    return rep.text


def get_data(html_text):
    final = []
    bs = BeautifulSoup(html_text, "html.parser")  # 创建BeautifulSoup对象
    body = bs.body  # 获取body部分
    data = body.find('div', {'id': '7d'})  # 找到id为7d的div
    ul = data.find('ul')  # 获取ul部分
    li = ul.find_all('li')  # 获取所有的li
    for day in li:  # 对每个li标签中的内容进行遍历
        temp = []
        date = day.find('h1').string  # 找到日期
        temp.append(date)  # 添加到temp中
        inf = day.find_all('p')  # 找到li中的所有p标签
        temp.append(inf[0].string, )  # 第一个p标签中的内容(天气状况)加到temp中
        if inf[1].find('span') is None:
            temperature_highest = None  # 天气预报可能没有当天的最高气温(到了傍晚,就是这样),需要加个判断语句,来输出最低气温
        else:
            temperature_highest = inf[1].find('span').string  # 找到最高温
            temperature_highest = temperature_highest.replace('℃', '')  # 到了晚上网站会变,最高温度后面也有个℃
        temperature_lowest = inf[1].find('i').string  # 找到最低温
        temperature_lowest = temperature_lowest.replace('℃', '')  # 最低温度后面有个℃,去掉这个符号
        temp.append(temperature_highest)  # 将最高温添加到temp中
        temp.append(temperature_lowest)  # 将最低温添加到temp中
        final.append(temp)  # 将temp加到final中
    return final


def write_data(data, name):
    file_name = name
    with open(file_name, 'a', errors='ignore', newline='') as f:
        f_csv = csv.writer(f)
        f_csv.writerows(data)

4.设置url并输出天气数据

if __name__ == '__main__':
    url = 'http://www.weather.com.cn/weather/101230501.shtml'
    html = get_content(url)
    result = get_data(html)
    write_data(result, 'weather.csv')

:如果要爬取其他城市的天气更换一下url即可

实验结果

程序不报错,且有weather.csv文件产生,数据包含一周的天气情况,且有最高气温和最低气温数据
在这里插入图片描述
在这里插入图片描述


总结

以上就是今天要讲的内容,本文仅仅简单介绍了如何爬取中国天气网中泉州一周的天气,包含当天的最高气温和最低气温,并保存到本地文件中,如果要更换城市做实验也可以按上述方法更换。
今天的分享就到这里啦,有不明白的小伙伴可以私信或留言哦~

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
好的,以下是实现这个功能的Python代码: ```python import requests import csv # 设置请求头,伪装成浏览器访问 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'} # 发送请求,获取长沙天气信息 url = 'http://www.weather.com.cn/weather/101250101.shtml' response = requests.get(url, headers=headers) response.encoding = 'utf-8' html = response.text # 解析HTML,获取长沙天气信息 from bs4 import BeautifulSoup soup = BeautifulSoup(html, 'html.parser') weather_list = soup.select('.t ul li') data_list = [] for weather in weather_list: date = weather.select('.time')[0].text detail_weather = weather.select('.wea')[0].text temperature = weather.select('.tem')[0].text.replace('\n', '').strip() wind_direction = weather.select('.win span')[0].text wind_power = weather.select('.win span')[1].text data_list.append([date, detail_weather, temperature, wind_direction, wind_power]) # 保存天气信息到csv文件 with open('weather.csv', 'w', encoding='utf-8', newline='') as f: writer = csv.writer(f) writer.writerow(['日期', '天气', '温度', '风向', '风力']) writer.writerows(data_list) ``` 以上代码,我们使用requests库发送请求,获取长沙天气信息的网页源代码。然后使用BeautifulSoup库解析HTML,从获取长沙天气信息。最后使用csv库将天气信息保存到csv文件。 可以根据需要修改代码的url、headers、保存的文件名等参数。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@¥文竹¥

你的鼓励是我最大的动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值