嵌套循环结构中列表无法追加的调试求助及代码排查
调试嵌套循环中URL列表未正确追加的问题
问题概述
代码意图从WeatherSpark的站点地图中提取指定城市的全年平均天气URL,但运行后仅返回匹配的站点地图页码,预期的URL列表url_site未被正确返回,且存在追加逻辑错误。
核心错误点
重复return语句导致URL列表无法返回
函数末尾先执行return matched_index,后续的return url_site永远不会被触发,这是url_site没被返回的直接原因。额外的错误追加操作
在for循环遍历loc之后,又执行了一次url_site.append(text),这里的text是for循环最后一次迭代的内容,会导致重复添加甚至错误的URL。重复导入requests库
代码开头两次导入requests,属于冗余操作,虽不影响功能但应清理。
修复后的代码
import requests from bs4 import BeautifulSoup import time def get_url(*args): matched_index = [] url_site = [] for a in args: city_country_match = False city_country = a.replace(" ","-") sitemap_index = 5 sitemap_index_max = 255 while not city_country_match: res = requests.get(f'https://weatherspark.com/sitemap-{sitemap_index}.xml') soup = BeautifulSoup(res.content,"xml") if city_country in res.text: city_country_match = True for loc in soup.select('loc'): text = loc.text if 'Average-Weather-in-' in text and 'Year-Round' in text and city_country in text: url_site.append(text) # 现在会正确匹配并追加目标URL print(f'找到{a}在第{sitemap_index}页') matched_index.append(sitemap_index) time.sleep(1.5) else: sitemap_index += 1 if sitemap_index == sitemap_index_max: print(f"未找到{city_country}") # 返回包含两个结果的元组,同时提供页码和URL列表 return matched_index, url_site # 调用函数并接收结果 page_indices, urls = get_url("Austin Texas United States", "Calgary Canada") print("匹配的页码:", page_indices) print("提取的URL列表:", urls)
修复说明
- 移除了重复的
requests导入语句 - 删除了for循环后多余的
url_site.append(text),避免重复添加 - 将两个return合并为返回一个元组,同时返回页码列表和URL列表,确保两个结果都能被获取
- 优化了变量递增的写法(
sitemap_index += 1替代sitemap_index = sitemap_index + 1)
内容的提问来源于stack exchange,提问作者WQureshi
相关产品推荐
相关产品推荐

