【问题标题】:Parsing XML: Finding Interesting Elements Using ElementTree解析 XML:使用 ElementTree 查找有趣的元素
【发布时间】:2015-08-25 14:17:29
【问题描述】:

我正在使用 urllib 和 ElementTree 来解析来自 pubmed 的 XML API 调用。

一个例子是:

#Imports Modules that can send requests to URLs 
#Python Version 3.4 Using IEP (Interactive Editor for Python) as IDE  
import urllib.request 
import urllib.parse 
import re 
import xml.etree.ElementTree as ET 
from urllib import request 

#Obtain API Call and assign Element Object to Root
id_request = urllib.request.urlopen('http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=pubmed&id=1757056')
id_pubmed = id_request.read()
root = ET.fromstring(id_pubmed)

我现在已经能够使用元素树将数据从 ET.fromstring 导入到对象根。我现在的问题是我无法从这个对象中找到有趣的元素。

我指的是: https://docs.python.org/2/library/xml.etree.elementtree.html 我的 XML 格式如下所示: http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=pubmed&id=1757056

我试过了:

#Parse Attempts.  Nothing returned.
for author in root.iter('Author'):
   print (author.attrib)

还有

#No Return for author
for author in root.findall('Id'):
   author = author.find('author').text
   print (author)

【问题讨论】:

    标签: python xml python-3.x xml-parsing pubmed


    【解决方案1】:

    尝试通过标签进行迭代

    for author in root.iter('Item'):
        if author.attrib['Name'] == 'Author':
        print("Success") 
    

    或者:

    author_list = [x for x in root.iter('Item') if x.attrib['Name'] == 'Author']
    

    不知道能不能按属性迭代

    【讨论】:

    • 嗯,两者都给了我无效的语法。
    【解决方案2】:

    .attrib 方法返回标签内的值。我想您可能想改用.tag.text。我不确定您要从这棵树中提取什么数据,但您也可以遍历 author 值。

    编辑: 那么 esummaryResult 标签似乎毫无意义,除非你会有更多的 DocSum 标签。但是您想要的信息在您的.text 值中。尝试打印author.tag,也许您可​​以检查返回的值是否符合您当前正在迭代的内容。

    【讨论】:

    • 在这种情况下,如果您查看 XML 链接:eutils.ncbi.nlm.nih.gov/entrez/eutils/… 我正在尝试提取嵌套在 Item Type = "List" Name = "AuthorList" 下面的 Authors 就像在 XML 中一样,我是希望迭代三位作者,然后用这种方法捕捉其他有趣的元素。
    猜你喜欢
    • 2018-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-07
    • 1970-01-01
    • 1970-01-01
    • 2021-02-06
    • 2017-08-31
    相关资源
    最近更新 更多