【问题标题】:python / BeautifulSoup use string value to access an child objet / tagpython/BeautifulSoup 使用字符串值访问子对象/标签
【发布时间】:2017-07-20 12:20:35
【问题描述】:

我正在使用 BeautifulSoup 在 python 中处理 XML 文件,以便处理具有类似结构的 XML 文件:

<xml>
  <headtag>
     <subtag1>textA</subtag1>
     <subtag2>textB</subtag2>
     <anothertag>textC</anothertag>
[...]

现在我需要访问一个特定的子对象,它通常看起来像这样:

print (BeautifulSoupObject.xml.headtag.subtag1.string)

但在我的情况下,我将子对象存储在一个字符串中,例如:

objIlikeToGet= 'xml.headtag.subtag1'

我喜欢做的是这样的事情(伪代码):

print (BeautifulSoupObject.objIlikeToGet.string)

所以我的问题是:如何使用字符串内容直接访问 BeautifulSoup-sub-object?

//顺便说一句:为什么我需要这个:我有一个配置文件,我在 objIlikeToGet 中定义了一些 xml 子对象,以根据使用的配置文件仅读取这个单一信息。这意味着一个脚本使用不同的配置文件并返回不同的信息。

【问题讨论】:

    标签: python xml string beautifulsoup


    【解决方案1】:

    我建议使用eval。确保输入来自您,而不是来自不受信任的来源。

    html = """<xml>
      <headtag>
     <subtag1>textA</subtag1>
     <subtag2>textB</subtag2>
     <anothertag>textC</anothertag>
     </headtag>
     </xml>"""
    
    soup = BeautifulSoup(html, 'lxml-xml')
    
    objIlikeToGet= "xml.headtag.subtag1"
    
    print(eval("soup." + objIlikeToGet + ".string"))
    

    输出:textA

    【讨论】: