【问题标题】:Python BeautifulSoup with Optional Tags带有可选标签的 Python BeautifulSoup
【发布时间】:2011-06-30 08:10:07
【问题描述】:

让我举个例子:

    from BeautifulSoup import BeautifulStoneSoup
    root = '''  <all2>
                    <images>
                        <image>
                            <name> Picture </name>
                            <url> www.thing.com</url>
                        </image>
                        <image> 
                            <name> Another one! </name>
                        </image>
                    </images>
                </all2>
                      '''

soup = BeautifulStoneSoup(root)
for img in soup.all2.images.findAll("image"):
    iname = img.i_name
    iurl = img.url
    print iname
    print iurl

让标签是可选的。在这种情况下,第二次迭代将找不到标签,并抛出异常:

AttributeError: 'NoneType' 对象没有属性 'renderContents'

如果没有出现可选标签,我希望 iurl 为 None。这可能吗?还是我的 XML 理解错误。

【问题讨论】:

    标签: python xml beautifulsoup


    【解决方案1】:

    你想要'nameTag'做什么???

    BeautifulSoup 文档清楚地告诉你使用

      iname = img.name.renderContents()
      iurl = img.url.renderContents()
    

    在这里发明新语法或语义的零理由

    【讨论】:

    • 我什么都没发明。它在文档中。 “这个习惯用法让您可以将第一个 标记作为 .fooTag 而不是 .foo 访问。例如,soup.table.tr.td 也可以表示为 soup.tableTag.trTag.tdTag,甚至是 soup.tableTag.tr .tdTag。如果您希望更明确地说明您正在做什么,或者如果您正在解析标签名称与 Beautiful Soup 方法和成员的名称冲突的 XML,这将非常有用。"
    • 关于使用 Tag 访问 '' 的文档在哪里?
    • 除此之外:您可以很容易地看到自己为不存在的标签返回 None 。并且在 None 上调用 renderContents() 显然会给您带来引用的错误。在这里使用 'if' 是你的朋友。
    • 所以解决方案是'if'或'try/catch'块?我曾考虑过这一点,但我认为会有更好的方法。我更改了上面的代码。现在它应该返回 None ,但我仍然无法从标签中提取数据而没有得到 AttributeError。
    • 这可能会做到:iname = (str(img.i_name.string) if (img.i_name != None) else None) iurl = (str(img.url.string) if (img .url != 无)否则无)
    猜你喜欢
    • 2019-10-18
    • 1970-01-01
    • 1970-01-01
    • 2016-01-10
    • 1970-01-01
    • 1970-01-01
    • 2013-09-19
    • 2021-05-17
    • 1970-01-01
    相关资源
    最近更新 更多