2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > 使用Python爬取中国天气网天气数据

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

时间:2021-09-19 15:19:08

相关推荐

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

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

注意:原文章写于12月

广州天气页面:/weather/101280101.shtml

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

使用Pycharm编写Python代码

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

编写python文件,引入Packages:

# -*- coding: UTF-8 -*-import requestsimport csvimport randomimport timeimport socketimport httplibfrom bs4 import BeautifulSoupimport sysreload(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'breakexcept 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的divul = data.find('ul', {'class':'t clearfix'})li = ul.find_all('li')# print lifor 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工具,文档为:/software/BeautifulSoup/bs4/doc/

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

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

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

程序主函数:

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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。