You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复Python 2/3中获取Rotana EPG数据时的IndexError: list index out of range?

问题分析与修复

错误根源

  1. 直接对re.findall的结果取[0],一旦正则匹配不到内容,空列表取索引会触发IndexError
  2. 未定义rotana函数,即使前面的问题解决,运行到调用处也会报错
  3. 原正则表达式的转义规则和网页实际结构不匹配,导致匹配失败

修复后的代码

# -*- coding: utf-8 -*-
import requests
import re

def rotana(date_str, channel_code):
    # 补充EPG数据处理逻辑,示例为下载CSV文件
    csv_url = f"https://rotana.net/triAssets/uploads/{date_str}/{channel_code}.csv"
    try:
        response = requests.get(csv_url)
        response.encoding = 'utf-8'
        # 这里可以添加保存到文件、解析EPG数据的逻辑
        print(f"成功获取频道 {channel_code} 的EPG数据")
    except Exception as e:
        print(f"获取频道 {channel_code} 数据失败: {str(e)}")

def main():
    target_url = 'https://rotana.net/%D8%AC%D8%AF%D9%88%D9%84-%D8%A7%D9%84%D8%A8%D8%B1%D8%A7%D9%85%D8%AC/'
    try:
        response = requests.get(target_url)
        response.encoding = 'utf-8'
        html_content = response.text
    except requests.exceptions.RequestException as e:
        print(f"请求网页失败: {str(e)}")
        return

    # 匹配日期,增加匹配失败的判断
    date_match = re.search(r'csv":"https://rotana.net/triAssets/uploads/(\d{4}-\d{2})/', html_content)
    if not date_match:
        print("未匹配到日期信息,请检查正则或网页结构")
        return
    date_str = date_match.group(1)

    # 匹配频道代码,优化正则并过滤无效项
    channel_codes = re.findall(r'/triAssets/uploads/\d{4}-\d{2}/(.*?)\.csv"', html_content)
    channel_codes = list(set([code for code in channel_codes if code and '.png' not in code]))
    
    if not channel_codes:
        print("未匹配到任何有效频道代码")
        return

    for code in channel_codes:
        rotana(date_str, code)

if __name__ == "__main__":
    main()

关键修改说明

  • 新增rotana函数的基础实现,可根据需求补充EPG数据的解析、存储逻辑
  • 对网络请求增加异常捕获,避免请求失败直接崩溃
  • 用re.search替代re.findall()[0],并判断匹配结果,彻底避免索引越界问题
  • 优化正则表达式,适配网页实际的URL格式(原正则的多余转义导致匹配失效)
  • 对频道代码列表做去重和有效性过滤,避免重复处理无效数据
  • 用main函数组织逻辑,代码结构更清晰易维护

内容的提问来源于stack exchange,提问作者Fair Bird

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 03:13:25