不幸的是,这会有点复杂,因为这种格式包含一些您需要的数据,而这些数据未包含在清晰的标记中。
数据模型
另外,您对嵌套的理解并不完全正确。实际的天主教堂结构(不是本文档结构)更像是:
District (also called deanery or vicariate. In this case they all seem to be Vicariates Forane.)
Cathedral, Parish, Oratory
请注意,尽管他们通常这样做,但没有要求教区属于区/教区。我认为该文件是说,在 District 之后列出的所有内容都属于该地区,但您无法确定。
那里还有一个入口,不是教堂而是社区(圣洛伦索菲律宾华人社区)。这些人在教会中没有明显的身份或治理(即它不是一座建筑物)——相反,它是一个牧师被分配照顾的非领土群体。
解析
我认为你应该采取渐进的方法:
- 找到所有
li元素,每个元素都是一个“项目”
- 项目名称是第一个文本节点
- 找到所有
i 元素:这些是键、属性值、列行等
- 直到下一个
i(由br 分隔)之前的所有文本都是该键的值。
这个页面的一个特殊问题是它的 html非常糟糕,你需要使用 MinimalSoup 来正确解析它。 特别是 BeautifulSoup认为 li 元素是嵌套的,因为文档中的任何位置都没有 ol 或 ul!
这段代码会给你一个元组列表。每个元组是一个项目的 ('key','value') 对。
一旦你有了这个数据结构,你就可以随心所欲地规范化、变换、嵌套等,并且把 HTML 留在后面。
from BeautifulSoup import MinimalSoup
import urllib
fp = urllib.urlopen("http://www.ucanews.com/diocesan-directory/html/ordinary-of-philippine-cagayandeoro-parishes.html")
html = fp.read()
fp.close()
soup = MinimalSoup(html);
root = soup.table.tr.td
items = []
currentdistrict = None
# this loops through each "item"
for li in root.findAll(lambda tag: tag.name=='li' and len(tag.attrs)==0):
attributes = []
parishordistrict = li.next.strip()
# look for string "district" to determine if district; otherwise it's something else under the district
if parishordistrict.endswith(' District'):
currentdistrict = parishordistrict
attributes.append(('_isDistrict',True))
else:
attributes.append(('_isDistrict',False))
attributes.append(('_name',parishordistrict))
attributes.append(('_district',currentdistrict))
# now loop through all attributes of this thing
attributekeys = li.findAll('i')
for i in attributekeys:
key = i.string # normalize as needed. Will be 'Address:', 'Parochial Victor:', etc
# now continue among the siblings until we reach an <i> again.
# these are "values" of this key
# if you want a nested key:[values] structure, you can use a dict,
# but beware of multiple <i> with the same name in your logic
next = i.nextSibling
while next is not None and getattr(next, 'name', None) != 'i':
if not hasattr(next, 'name') and getattr(next, 'string', None):
value = next.string.strip()
if value:
attributes.append((key, value))
next = next.nextSibling
items.append(attributes)
from pprint import pprint
pprint(items)