我正在参加数据科学课程介绍,我的第一个任务是从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?