Python TypeError求助:NoneType对象无len(),断言列表长度失败
解决TypeError: object of type 'NoneType' has no len()的问题
嘿,这个问题其实很典型——你的get_links函数没有返回值!Python里如果函数没写return语句,默认会返回None,所以你把page赋值成了None,自然调用len(page)就会触发这个错误啦。
第一步:给函数添加返回语句
最核心的修复是让get_links返回你创建的list_links列表,修改后的代码如下:
from datetime import datetime response = links # 假设这里的links是已经获取到的有效响应对象 def get_links(response): list_links = [] for i in range(len(response)): url = response[i].select('a')[0]['href'] date_str = response[i].select('span.field-content')[1].text date = datetime.strptime(date_str, '%A, %B %d, %Y') list_links.append((url, date)) # 关键:返回构建好的列表 return list_links page = get_links(response) assert len(page) == 50
第二步:额外的稳健性优化建议
为了避免循环中因为选择器找不到元素直接崩溃,你可以加一些容错处理,让代码更健壮:
def get_links(response): list_links = [] # 直接遍历response元素,比用range(len(response))更简洁 for item in response: # 检查是否找到目标a标签 a_tags = item.select('a') if not a_tags: print(f"第{response.index(item)}条数据未找到a标签,跳过") continue url = a_tags[0]['href'] # 检查是否有足够的span元素 span_tags = item.select('span.field-content') if len(span_tags) < 2: print(f"第{response.index(item)}条数据span标签不足,跳过") continue date_str = span_tags[1].text # 捕获日期格式解析错误 try: date = datetime.strptime(date_str, '%A, %B %d, %Y') list_links.append((url, date)) except ValueError: print(f"第{response.index(item)}条数据日期格式错误:{date_str},跳过") continue return list_links
这样即使部分条目不符合预期,程序也能继续运行,还能帮你快速定位出问题的数据。
内容的提问来源于stack exchange,提问作者user4687733




