我在解析人口数量并将其添加到列表中时遇到了困难 从bs4导入* 导入请求
def getPopulation(name):
url="http://www.worldometers.info/world-population/"+name+"-population/"
data=requests.get(url)
soup=BeautifulSoup(data.text,"html.parser")
#print(soup.prettify())
x=soup.find_all('div',{"class":"col-md-8 country-pop-description"})
y=x[0].find_all('strong')
result=y[1].text
return result
def main():
no=input("Enter the number of countries : ")
Map=[]
for i in range(0,int(no)):
country=input("Enter country : ")
res=getPopulation(country)
Map.append(res)
print(Map)
if __name__ == "__main__":
main()
如果我通过传递一个国家名(如“india”)作为参数来单独运行该函数,那么该函数工作得很好,但是在这个程序中编译时显示了一个错误。你知道吗
Traceback (most recent call last):
File "C:/Users/Latheesh/AppData/Local/Programs/Python/Python36/Population Graph.py", line 24, in <module>
main()
File "C:/Users/Latheesh/AppData/Local/Programs/Python/Python36/Population Graph.py", line 19, in main
res=getPopulation(country)
File "C:/Users/Latheesh/AppData/Local/Programs/Python/Python36/Population Graph.py", line 10, in getPopulation
y=x[0].find_all('strong')
IndexError: list index out of range
我刚刚运行了您的代码,用于示例案例(印度和中国),没有遇到任何问题。得到indexer的原因是如果find\u all没有结果,结果将是
[]
(因此没有第0个元素)。你知道吗要修复代码,您需要一个“catch”来确认是否有结果。下面是一个基本方法:
一种更简洁的写入方法,消除不必要的holder变量(例如y)并使用三元运算符:
关于代码的其他注意事项:
return Map
,而不是使用print(Map)
url
,最好使用字符串格式插入变量。例如,"http://www.worldometers.info/world-population/{}-population/".format(name)
相关问题 更多 >
编程相关推荐