提问人:PracticingPython 提问时间:5/14/2021 更新时间:5/14/2021 访问量:66
从 xml 中的元素中提取属性
Extracting attributes from elements in xml
问:
我有一个脚本,可以从许多 xpath 中提取文本和属性。每个条目的数据在提取时都会附加到列表中(所有属性后跟文本,然后移动到下一个 xpath),然后将该列表插入到数据框中。我的问题是,并非每个条目都具有每个xpath的相同属性。因此,例如,所有条目都具有元素和至少一个相应的属性(颜色)(即,但是某些 cat 元素可能具有并非所有 cat 元素都具有的附加属性(即 )。当行插入到数据框中时,这会带来一个问题,因为长度与列数不匹配。除非缺少一个属性,否则属性的顺序将保持统一。我需要一种方法来插入一个空白字符串,当一个属性因为不在元素中而被有效跳过时。
for next_url in next_url_list:
response = urllib.request.urlopen(next_url)
bytes_ = response.read()
root = xml.etree.ElementTree.fromstring(bytes_)
for count in range(0,len(root.findall("./xpath:entry", namespaces=namespaces))):
for xpath in xpaths:
try:
attribs = list(root.findall(xpath,namespaces=namespaces)[count].attrib.keys())
for attrib in attribs:
award.append(root.findall(xpath, namespaces=namespaces)[count].attrib[attrib])
award.append(root.findall(xpath, namespaces=namespaces)[count].text)
except IndexError:
pass
答:
1赞
wwii
5/14/2021
#1
我需要一种方法来插入一个空白字符串,当一个属性因为不在元素中而被有效跳过时。
- 对于每个元素,使用空字符串为值创建预期属性的字典。
-
{'a1':'','a2':'',...}
-
- 从元素中提取属性时,请更新字典值
- 使用字典构造行 - 缺少的属性将具有空字符串作为值。
评论