简体   繁体   中英

Python: Get attributes

If I've got an xml-tag like this:

  <article n="1" translation="Year_1973_fr.xml:1">

How can I access the "translation"-Attribute?

It's no problem to access the "n"-attribute, I simply do the following: s.attrib["n"]

Thanks for any advice.

.attrib["translation"] works:

>>> from xml.etree import ElementTree as ET
>>> data = '<article n="1" translation="Year_1973_fr.xml:1"/>'
>>> element = ET.fromstring(data)
>>> element.attrib
{'translation': 'Year_1973_fr.xml:1', 'n': '1'}
>>> element.attrib['translation']
'Year_1973_fr.xml:1'

For example using BeautifulSoup :

html_doc = """
 <article n="1" translation="Year_1973_fr.xml:1">
"""
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc)
print soup.article['translation']
Year_1973_fr.xml:1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM