python 网络爬虫 1.3 获取中国天气网8-15天的天气信息,包含: 日期,天气,温度,风力. 将数据存入文档。

题目:
获取中国天气网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')

输出结果:

  • 3
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值