我正在參加數據科學課程介紹,我的第一個任務是從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?