使用爬虫(lxml)+requests收集厦门2016-2020每一天的历史天气信息

使用爬虫(lxml)+requests收集厦门2016-2020每一天的历史天气信息

get_month_data

  1. 函数作用:得到每个月的数据集合,并返回一个pd.DataFrame。
  2. 其中使用了xpath的方式提取数据
    etree_html = etree.HTML(html.text)
    content = etree_html.xpath(Xpath) # content是一个list
    
  3. 使用numpy对数据reshape
  4. 将数据转换到DataFrame中

get_month_html

  1. 函数作用:得到每个月的链接集合。
  2. 通过几次尝试,发现该网站的命名规律是https://lishi.tianqi.com/城市拼音/年份月份.html(例如:https://lishi.tianqi.com/xiamen/201606.html)
  3. 简单的一个for循环搞定

完整代码

import requests
import numpy as np
import pandas as pd
from lxml import etree

def get_month_data(html, xpath, xpath_num): # 得到每个月的数据集合
    df = pd.DataFrame([])
    etree_html = etree.HTML(html.text)
    for i, Xpath in enumerate(xpath):
        content = etree_html.xpath(Xpath)
        content = np.array(content) # 将得到的content数据转成numpy
        content = content.reshape((len(content)//xpath_num[i],xpath_num[i])) # 根据得到的序列数量reshape
        # print(content)
        df[content[0]] = content[1:] # 放进DataFrame中,content[0]是columns的名字,content[1:]是内容
    print(df)
    return df

def get_month_html(link_base, start_year, end_year): # 网站的天气数据有规律
    link_collection=[]
    for year in range(start_year, end_year+1):
        for month in range(1,13):
            if month < 10: #把1,2,3月份等补充为01,02,03月份,10,11等月份就不需要补0
                link = link_base+str(year)+'0'+str(month)
            else:
                link = link_base+str(year)+str(month)
            link+='.html'
            link_collection.append(link)
    # print(link_collection)
    return link_collection

if __name__ == '__main__':
    start_year = 2016 # 数据的起始年份
    end_year = 2020 # 数据的终止年份
    link_base = 'https://lishi.tianqi.com/xiamen/' # 基准链接
    xpath = ["//div[@class='th200']/text()","//div[@class='th140']/text()"] # 通过xpath的方式手工得到,第一条是日期,第二条是天气数据(最高温,最低温,天气情况,风力)
    xpath_num = [1,4] # 对应xpath的标签,第一条只有日期(1条信息),第二条link(4条信息,见上一行)
    headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'} # 伪装成用户
    link_collection = get_month_html(link_base,start_year,end_year) # 得到链接集合
    weather_collection = pd.DataFrame([])
    for link in link_collection:
        html = requests.get(url=link, headers=headers)
        df = get_month_data(html, xpath,xpath_num)
        weather_collection = weather_collection.append(df,ignore_index=True) # 将得到的从start_year到end_year的每日信息拼接到一个大的DataFrame中

    weather_collection.to_csv('./2016-2020天气汇总.csv', encoding='gbk', index=False) # 保存到csv
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值