遍历li_all里面的值

该代码段使用Python的requests和lxml库解析HTML,从特定网页抓取天气预报信息,包括日期、天气状况、最低和最高气温。数据处理后存储到PandasDataFrame,最后转换为Excel格式。
摘要由CSDN通过智能技术生成

忘了的时候记得翻出来看看

def get_data_7(url):
    html = res_text(url)
    list_s = html.xpath('//*[@id="7d"]/ul/li')  # 获取天气数据列表
    Date, Weather, Low, High = [], [], [], []
    for i in range(len(list_s)):
#----------------------------根据i还有[0]的遍历用法
        list_date = list_s[i].xpath('./h1/text()')[0]  # 获取日期,如:4日(明天)
        # print(list_data)
        list_weather = list_s[i].xpath('./p[1]/@title')[0]  # 获取天气情况,如:小雨转雨夹雪
        # print(list_weather)
        tem_low = list_s[i].xpath('./p[2]/i/text()')  # 获取最低气温
        tem_high = list_s[i].xpath('./p[2]/span/text()')  # 获取最高气温
        if tem_high == []:  # 遇到夜晚情况,筛掉当天的最高气温
            tem_high = tem_low  # 无最高气温时,使最高气温等于最低气温
        tem_low = int(tem_low[0].replace('℃', '')) # 将气温数据处理
        tem_high = int(tem_high[0].replace('℃', ''))
        # print(type(tem_high))
        Date.append(list_date), Weather.append(list_weather), Low.append(tem_low), High.append(tem_high)
    excel = pd.DataFrame()  # 定义一个二维列表
    excel['日期'] = Date
    excel['天气'] = Weather
    excel['最低气温'] = Low
    excel['最高气温'] = High
    # print(excel)
    return excel

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值