天气数据爬取并存cvs

4 篇文章 0 订阅
1 篇文章 0 订阅
import requests
from requests.exceptions import RequestException
from bs4 import BeautifulSoup
import os
import csv
import time

def get_one_page(url):
    '''
    获取网页
    '''
    print('正在加载'+url)
    headers={'User-Agent':'User-Agent:Mozilla/5.0'}
    try:
        response = requests.get(url,headers=headers)
        if response.status_code == 200:
            return response.content
        return None
    except RequestException:
        return None

def parse_one_page(html):
    '''
	对网页内容进行解析
	'''
    soup = BeautifulSoup(html,  "lxml")
    info = soup.find('div',  class_='wdetail')
    rows=[]
    tr_list = info.find_all('tr')[1:]       # 使用从第二个tr开始取
    for index,  tr in enumerate(tr_list):     # enumerate可以返回元素的位置及内容
        td_list = tr.find_all('td')
        date = td_list[0].text.strip().replace("\n", "")  # 取每个标签的text信息,并使用replace()函数将换行符删除
        weather = td_list[1].text.strip().replace("\n", "").split("/")[0].strip()
        temperature_high = td_list[2].text.strip().replace("\n",  "").split("/")[0].strip()
        temperature_low = td_list[2].text.strip().replace("\n",  "").split("/")[1].strip()

        rows.append((date,weather,temperature_high,temperature_low))
    return rows



# cities = ['chengdu','aba','bazhong','dazhou','deyang','ganzi','guangan',
#           'guangyuan','leshan','luzhou','meishan','mianyang','neijiang','nanchong',
#           'panzhihua','scsuining','yaan','yibin','ziyang','zigong','liangshan']
# years = ['2012','2013','2014','2015','2016','2017','2018']

cities = ['beijing']
years = ['2014','2015','2016','2017','2018','2019','2020','2021']
months = ['01','02','03','04','05','06', '07', '08','09','10','11','12']

if __name__ == '__main__':
    # os.chdir()  # 设置工作路径
    for city in cities:
        with open(city + '_weather.csv', 'a', newline='') as f:
            writer = csv.writer(f)
            writer.writerow(['date','weather','temperature_high','temperature_low'])
            for year in years:
                for month in months:
                    url = 'http://www.tianqihoubao.com/lishi/'+city+'/month/'+year+month+'.html'
                    html = get_one_page(url)
                    content=parse_one_page(html)
                    writer.writerows(content)
                    print(city+year+month+' is OK!')
                    time.sleep(2)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值