2017-02-09 53 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