使用Python爬取中国天气网天气数据

使用Python获取中国天气网中“广州”天气数据

注意:原文章写于2016年12月

广州天气页面:http://www.weather.com.cn/weather/101280101.shtml

image

了解该页面的HTML结构和需要的数据,这里抓取的为时间、该城市的天气内容、最低最高温度(如果有的情况下)。

image

使用Pycharm编写Python代码

创建项目并安装需要的Package:

image

编写python文件,引入Packages:

# -*- coding: UTF-8 -*-
import requests
import csv
import random
import time
import socket
import httplib
from bs4 import BeautifulSoup
import sys
reload(sys)
sys.setdefaultencoding( "utf-8" )

说明如下:

  • requests:获取页面的HTML源码
  • csv:将获取的数据写入csv文件中
  • random:获取随机数
  • time:时间的相关操作
  • socket,httplib:这里用于异常状况的处理(注:在python3.0版本之前,使用的是httplib包,在此之后,使用的为http.client包,详情见:)
  • BeautifulSoup:用来代替正则式获取源码中相应HTML标签中的内容

获取网页中的HTML代码:

def get_content(url, data=None):
    header = {
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
        'Accept-Encoding': 'gzip, deflate, sdch',
        'Accept-Language': 'zh-CN,zh;q=0.8',
        'Connection': 'keep-alive',
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.235'
    }
    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 httplib.BadStatusLine as e:
            print ('5:', e)
            time.sleep(random.choice(range(30, 80)))
        except httplib.IncompleteRead as e:
            print ('6:', e)
            time.sleep(random.choice(range(5, 15)))
    return rep.text

其中:

  • header:request.get函数中一个参数,目的是模拟浏览器访问该页面
  • timeout:设定一个超时的时间,取随机数是为了防止被网站认定爬虫操作
  • rep.encoding = ‘utf-8’:将源代码的编码格式设定为UTF-8,否则会导致中文乱码

从HTML标签中获取需要的内容数据:

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', {'class':'t clearfix'})
    li = ul.find_all('li')
    # print li

    for day in li: # 对每个li标签中的内容进行遍历
        temp = []
        # 这里有问题
        date = day.find('h1').string # 找到日期
        temp.append(date)
        inf = day.find_all('p') # 找到li标签中所有的p标签
        temp.append(inf[0].string) # 将第一个p标签中的内容(天气状况)加入到temp中
        if inf[1].find('span') is None:
            temperature_higgest = None # 天气预报可能没有当天的最高气温(到了傍晚,就是这样),需要加一个判断,来输出最低气温
        else:
            temperature_higgest = inf[1].find('span').string # 找到最高气温
            # temperature_higgest = temperature_higgest.replace('℃', '') # 到了晚上网站内容会有变动,去掉这个符号
        temperature_lowest = inf[1].find('i').string # 找到最低温度
        # temperature_lowest = temperature_lowest.replace('℃', '')
        temp.append(temperature_higgest)
        temp.append(temperature_lowest)
        final.append(temp)
    return final

这里主要用到了BeautifulSoup工具,文档为:http://www.crummy.com/software/BeautifulSoup/bs4/doc/

从上述网页中的HTML结构可知,我们需要得到id=’7d’的div的ul,日期数据在该ul中的h1标签中,天气情况在该ul的p标签中,最高温度和最低温度在每个li的span和i标签中。

将获取到的数据写入CSV文件:

# 将数据抓取到的文件写入文件
def write_data(data, name):
    file_name = name
    with open(file_name, 'w') as f:
        f_csv = csv.writer(f)
        f_csv.writerows(data)

程序主函数:

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

 

  • 6
    点赞
  • 107
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,您想了解如何用 Python 爬取历史天气数据,是吗? 首先,需要确定您想要爬取哪个地区的历史天气数据。一般来说,可以通过查询该地区的气象局或气象站获取历史天气数据。 接着,可以使用 Python 中的 requests 库来发送 HTTP 请求,获取页源代码。然后,可以使用 BeautifulSoup 库来解析页源代码,提取出所需的天气数据。 以下是一个简单的示例代码,用于爬取中国天气上北京市 2019 年 1 月份的历史天气数据: ``` python import requests from bs4 import BeautifulSoup url = 'http://www.weather.com.cn/weather/101010100.shtml#dt' 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'} r = requests.get(url, headers=headers) r.encoding = 'utf-8' soup = BeautifulSoup(r.text, 'html.parser') weather_list = soup.select('.t li') for weather in weather_list: date = weather.select('.time')[0].text weather_detail = weather.select('.temp')[0].text.strip() print(date, weather_detail) ``` 以上代码中,我们首先通过 requests 库发送了一个 GET 请求,获取了北京市天气页源代码。然后,使用 BeautifulSoup 库解析页源代码,提取出了 2019 年 1 月份的天气数据,并打印输出了日期和天气详情。 需要注意的是,不同的页结构不同,需要根据具体情况修改代码。同时,需要注意站的 robots.txt 文件,不要过度访问站,以免被封 IP 或其他限制。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值