题目:
获取中国天气网8-15天的天气信息,包含: 日期,天气,温度,风力. 将数据存入文档。
代码:
from requests_html import HTMLSession
url = "http://www.weather.com.cn/weather15d/101190401.shtml"
# 获取请求对象
session = HTMLSession()
response = session.get(url)
html = response.html
div = html.xpath('//*[@class="t clearfix"]', first=True)
div_list = div.xpath('//li')
result_list = []
for d in div_list:
time = d.xpath('//span[1]/text()', first=True)
wea = d.xpath('//span[2]/text()', first=True)
tem1 = d.xpath('//span[3]/em/text()', first=True)
tem2 = d.xpath('//span[3]/text()', first=True)
wind = d.xpath('//span[4]/text()', first=True)
wind1 = d.xpath('//span[5]/text()', first=True)
data = {
"日期": time,
"天气": wea,
"温度": tem1 + tem2,
"风向": wind,
"风力等级": wind1,
}
result_list.append(data)
print(result_list)
with open('data/weather.txt', 'w+', encoding='utf-8') as f:
for i in result_list:
f.write(str(i))
f.write('\n')
输出结果: