Python 怎样将爬取的天气数据保存为json文件?

ajunajun 2019-08-18 10:03:10
麻烦修改下面的代码,想实现:从配置文件里读取城市名称和保存路径,爬取指定城市的7天天气预报并以json格式保存到指定路径下。
爬取天气预报的代码如下:

import requests
from bs4 import BeautifulSoup
import re
import json

def get_page(url):
try:
kv = {'user-agent':'Mozilla/5.0'}
r = requests.get(url,headers = kv)
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text
except:
return '错误'

def parse_page(html, return_list):
soup = BeautifulSoup(html, 'html.parser')
day_list = soup.find('ul', 't clearfix').find_all('li')
for day in day_list:
date = day.find('h1').get_text()
wea = day.find('p', 'wea').get_text()
if day.find('p', 'tem').find('span'):
hightem = day.find('p', 'tem').find('span').get_text()
else:
hightem = ''
lowtem = day.find('p', 'tem').find('i').get_text()
#win = re.search('(?<= title=").*?(?=")', str(day.find('p','win').find('em'))).group()
win = re.findall('(?<= title=").*?(?=")', str(day.find('p','win').find('em')))
wind = '-'.join(win)
level = day.find('p', 'win').find('i').get_text()
return_list.append([date, wea, lowtem, hightem, wind, level])
#return return_list

def print_res(return_list):
tplt = '{0:<10}\t{1:^10}\t{2:^10}\t{3:{6}^10}\t{4:{6}^10}\t{5:{6}^5}'
print(tplt.format('日期', '天气', '最低温', '最高温', '风向', '风力',chr(12288)))
for i in return_list:
print(tplt.format(i[0], i[1],i[2],i[3],i[4],i[5],chr(12288)))

def main():
url = 'http://www.weather.com.cn/weather/101110101.shtml'
html = get_page(url)
wea_list = []
parse_page(html, wea_list)
print_res(wea_list)

if __name__ == '__main__':
main()


配置文件SpWeather.ini内容如下:
[CityAndDir]
City=哈尔滨
OutSet=D:\WeatherResult\weather.json

打印出来的结果是这样的:

json文件中不要标题部分。

非常感谢!!!
...全文
589 3 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
罗卜基斯 2019-08-20
  • 打赏
  • 举报
回复
少设置参数: json.dump(json_data, result_file, ensure_ascii=False, indent=4) 这样文本会显示层次结构
ajunajun 2019-08-19
  • 打赏
  • 举报
回复
搞了一晚上做成了这个样子,但怎么根据配置文件中的城市信息爬取还不会,麻烦帮忙改改,感谢

import requests
import bs4 as bs
from prettytable import PrettyTable
import json
#导入读配置文件模块
import os
import configparser
#---------------------------------------------------------
#读配置文件
#---------------------------------------------------------
# 项目路径
rootDir = os.path.split(os.path.realpath(__file__))[0]
# 配置文件路径
configFilePath = os.path.join(rootDir, 'SpWeather.ini')
def get_config_values(section, option):
"""
根据传入的section获取对应的value
:param section: ini配置文件中用[]标识的内容
:return:
"""
WechapGroup = configparser.ConfigParser()
WechapGroup.read(configFilePath)
# return config.items(section=section)
return WechapGroup.get(section=section, option=option)
#---------------------------------------------------------
#获取配置文件中【城市】信息
TheCiy = get_config_values('CityAndDir', 'TheCity')
#获取配置文件中【保存目录】信息
OutDir = get_config_values('CityAndDir', 'OutDir')
#********************************************************************
url = "http://www.weather.com.cn/weather/101110101.shtml"
header = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.87 Safari/537.36"
}

weathers = ["日期", "天气", "最低温", "最高温", "风向", "风力"]
table = PrettyTable(weathers)
json_data = []

res = requests.get(url, header)
if res.status_code == 200:
soup = bs.BeautifulSoup(res.content.decode("utf-8"), "lxml")
for el in soup.select(".c7d ul li.skyid"):

row = []
row.append(el.select_one("h1").get_text())
row.append(el.select_one(".wea").get_text())
row.append(el.select_one(".tem i").get_text())
high = el.select_one(".tem span")
row.append(high.get_text() if high else "")
row.append("-".join([win.get("title") for win in el.select(".win span")]))
row.append(el.select_one(".win i").get_text())
table.add_row(row)

data = {}
data['date'] = el.select_one("h1").get_text()
data['weather'] = el.select_one(".wea").get_text()
data['tem_low'] = el.select_one(".tem i").get_text()
data['tem_high'] = high.get_text() if high else ""
data['wind_direction'] = "-".join([win.get("title") for win in el.select(".win span")])
data['wind-force'] = el.select_one(".win i").get_text()
json_data.append(data)


_json = json.dumps(json_data, ensure_ascii=False)
print(_json)
with open(OutDir, 'w') as result_file:
json.dump(json_data, result_file, ensure_ascii=False)


SpWeather.ini配置文件内容如下:
[CityAndDir]
TheCity=哈尔滨
OutDir=D:\Weather.json

json文件结果如下:

能不能每天一行显示?
Italink 2019-08-19
  • 打赏
  • 举报
回复
1、它这个是每个城市都有自己的编号,你可以用爬虫获取这些城市编号,也可以自己翻源码构建存储一下,运行的时候读取为一个字典,这样的话就根据配置文件进行爬取某一城市,比如你的网址:http://www.weather.com.cn/weather/101110101.shtml
其中的101110101就是西安的编码
2、你是说控制台上逐行显示吗?你单独打印列表就可以了
for i in json_data:
print(i)

json文件逐行显示没必要,因为这个文件毕竟不是最终给人看的,而是给代码处理的,你加换行反倒不容易处理

37,743

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • WuKongSecurity@BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧