2017-02-09 52 views
2

我正在参加数据科学课程介绍,我的第一个任务是从CIA World Factbook的每个国家/地区页面额外添加某些数据字段。尽管我最近已经意识到有更简单的方法来查找数据,但我想通过我的最初思考过程进行跟踪,具体如下。循环迭代BeautifulSoup分析树元素列表太早结束

我开发了迭代结果的函数:

for link in fulllink: 
with urlopen(link) as countrypage: 
    countrysoup = BeautifulSoup(countrypage, "lxml") 
    data = countrysoup.find_all(class_="category_data") 

我已经证实,如果一个国家页面上,我需要字符串值,他们将出现在“数据”。下面的函数接受一个标签,并使用.parent和.previous_sibling来确定附加到标签的字符串值是我想要提取的字符串值。

def get_wfb_data(x): 
country_data = [0,0,0,0] 
for tag in x: 
    try: 
     if 'Area:' in tag.parent.previous_sibling.previous_sibling.strings and 'total: ' in tag.parent.strings: 
      country_data[0]=tag.string 
     elif 'GDP (purchasing power parity):' in tag.previous_sibling.previous_sibling.strings: 
      country_data[1]=tag.string 
     elif 'Roadways:' in tag.parent.previous_sibling.previous_sibling.strings and 'total: ' in tag.parent.strings: 
      country_data[2]=tag.string 
     elif 'Railways:' in tag.parent.previous_sibling.previous_sibling.strings and 'total: ' in tag.parent.strings: 
      country_data[3]=tag.string 
     else: 
      continue 
    except: 
     pass 

return country_data 

异常处理用于处理没有这些属性并因此引发异常的NavigableString对象。在零列表中替换值允许我处理特定区域没有数据列在我有兴趣提取的四个类别之一中的情况。此外,定义为四个独立的功能,各自的标准工作,但一起非常缓慢,因为列表必须在我们的时代最多迭代。然而,这个函数的最终结果总是一个列表,其中第一个零已被替换,但其他的不一样如下 [“Total Area#”,0,0,0]。

我相信循环在第一个if语句与x中的标签匹配之后终止,我该如何修复我的函数以继续向下x?

回答

1

我做你正在做这个调用的假设:get_wfb_data(data)

你的功能从来没有失败,它只是从来没有你的条件,其他部分相匹配。

我试图在几个不同的链接(包含各为GDP,道路等数据)

经检查X的长度,并通过对循环中,您可以放心的印刷循环的数量在匹配第一个条件后,循环未终止,然后无法到达最后一个数据元素。事实上,剩下的条件是永远不会满足的。

def get_wfb_data(x): 
    country_data = [0, 0, 0, 0] 
    print(len(x)) 
    i = 0 
    for tag in x: 
     i += 1 
     try: 
      if 'Area:' in tag.parent.previous_sibling.previous_sibling.strings \ 
        and 'total: ' in tag.parent.strings: 
       country_data[0] = tag.string 
      elif 'GDP (purchasing power parity):' in tag.previous_sibling.previous_sibling.strings: 
       country_data[1] = tag.string 
      elif 'Roadways:' in tag.parent.previous_sibling.previous_sibling.strings \ 
        and 'total: ' in tag.parent.strings: 
       country_data[2] = tag.string 
      elif 'Railways:' in tag.parent.previous_sibling.previous_sibling.strings \ 
        and 'total: ' in tag.parent.strings: 
       country_data[3] = tag.string 
      else: 
       continue 
     except: 
      pass 
    print(str(i)) 
    return country_data