1

I am trying to parse xml in python but I keep on getting this error: TypeError: 'str' object is not callable on line 10 "print("Date:", tree.find('date').text())"

My code is as follows:

import xml.etree.ElementTree as ET

data = '''<person>
<date>Wednesday, Oct 14 2020 1:03AM</date>
<email hide="yes" />
<username>John Doe</username>
</person>'''


tree = ET.fromstring(data)
print("Date:", tree.find('date').text())
print("Email attr:", tree.find('email').get('hide'))

Thank you in advance.

1
  • 1
    date is of type xml.etree.ElementTree.Element and text is an attribute , not a function. Hence the error not callable. date.text will work instead of date.text() Commented Oct 24, 2020 at 9:01

2 Answers 2

2

Remove () after the .text:

import xml.etree.ElementTree as ET

data = '''<person>
<date>Wednesday, Oct 14 2020 1:03AM</date>
<email hide="yes" />
<username>John Doe</username>
</person>'''


tree = ET.fromstring(data)
print("Date:", tree.find('date').text)  # <-- only `.text`
print("Email attr:", tree.find('email').get('hide'))

Prints:

Date: Wednesday, Oct 14 2020 1:03AM
Email attr: yes
Sign up to request clarification or add additional context in comments.

Comments

1

You should remove the () after .text because this is an attribute not method:

print("Date:", tree.find('date').text)
print("Email attr:", tree.find('email').get('hide'))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.