@Robin_TY《零基础Python入门》最后一章爬取各个城市的AQI老是报错,说主函数main()错了,还说第一个定义的div_content = div_list[i]有问题, 还有本文第45行city_aqi = get_city_aqi(city_pinyin)有问题,不知道什么问题?

import requests from bs4 import BeautifulSoup def get_city_aqi(city_pinyin): # 城市的AQI url = 'http://pm25.in/' + city_pinyin r = requests.get(url, timeout=30) soup = BeautifulSoup(r.text, 'lxml') div_list = soup.find_all('div', {'class': 'span1'}) city_aqi = [] for i in range(8): div_content = div_list[i] caption = div_content.find('div', {'class': 'caption'}).text.strip() value = div_content.find('div', {'class': 'value'}).text.strip() city_aqi.append((caption, value)) return city_aqi def get_all_cities(): url = 'http://pm25.in/' city_list = [] r = requests.get(url, timeout=30) soup = BeautifulSoup(r.text, 'lxml') city_div = soup.find_all('div', {'class': 'bottom'})[1] city_link_list = city_div.find_all('a') for city_link in city_link_list: city_name = city_link.text city_pinyin = city_link['href'][1] city_list.append((city_name, city_pinyin)) return city_list def main(): """ 主函数 """ city_list = get_all_cities() for city in city_list: city_name = city[0] city_pinyin = city[1] city_aqi = get_city_aqi(city_pinyin) print(city_name, city_aqi) if __name__ == '__main__': main()

Jessicaly

赞同来自: wangxiaolei

用debug检查出来了,显示城市拼音获取只有一个a,我就发现32行后面应该是1:,就是除掉前面的第一个字符斜杠,后面所有都是城市拼音,这样就对了

要回复问题请先登录注册