python中的列表追加和web爬行困难

2024-06-28 19:35:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我在解析人口数量并将其添加到列表中时遇到了困难 从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

Tags: nameinmapmainlocalresallfind
1条回答
网友
1楼 · 发布于 2024-06-28 19:35:41

我刚刚运行了您的代码,用于示例案例(印度和中国),没有遇到任何问题。得到indexer的原因是如果find\u all没有结果,结果将是[](因此没有第0个元素)。你知道吗

要修复代码,您需要一个“catch”来确认是否有结果。下面是一个基本方法:

def getPopulation(name):
    ...
    x=soup.find_all('div',{"class":"col-md-8 country-pop-description"})
    if x:
        y=x[0].find_all('strong')
        result=y[1].text
    else:
        result = "No results founds."
    return result

一种更简洁的写入方法,消除不必要的holder变量(例如y)并使用三元运算符:

def getPopulation(name):
    ...
    x=soup.find_all('div',{"class":"col-md-8 country-pop-description"})

    return x[0].find_all('strong')[1].text if x else "No results founds."

关于代码的其他注意事项:

  1. 最好对所有函数都使用returns。对于main(),应该使用return Map,而不是使用print(Map)
  2. Python中的样式约定要求变量名为小写(例如Map应该是Map),并且在返回行之前应该有一个空格(如上面缩短的getPopulation()所示)。我建议复习PEP 8以了解更多关于样式规范/使代码更易于阅读的知识。你知道吗
  3. 对于url,最好使用字符串格式插入变量。例如,"http://www.worldometers.info/world-population/{}-population/".format(name)

相关问题 更多 >