문서 및 기타 유사한 질문을 살펴 보았고 여기서 무엇이 잘못되었는지 해결할 수 없습니다!
API의 XML 출력을 사용하고 싶습니다.
다음과 같은 XML이 있습니다.
<response>
<lst></lst>
<result>
<doc>
<str name ="pa">1234</str>
<str name ="et">Title 1</str>
<str name ="pb">Publisher 1</str>
<str name ="ur">http://www.exampleone.com</str>
</doc>
<doc>
<str name ="pa">5678</str>
<str name ="et">Title 2</str>
<str name ="pb">Publisher 2</str>
<str name ="ur">http://www.exampletwo.com</str>
</doc>
</result>
각 문서 요소에 대한 "pa"를 얻고 싶습니다.
이것은 내가 사용하는 코드이지만 아무것도 얻지 못합니다.
import requests
import xml.etree.ElementTree as ET
r = requests.get("api url goes here")
tree = ET.fromstring(r.content)
for doc in tree.findall("doc"):
pan = doc.find('pa').text
print pan
내가 무엇을 잘못하고 있지?
이것은 작동합니다 ...
import xml.etree.ElementTree as ET
resp = '''<response><lst></lst><result><doc>
<str name ="pa">1234</str>
<str name ="et">Title 1</str>
<str name ="pb">Publisher 1</str>
<str name ="ur">http://www.exampleone.com</str>
</doc>
<doc>
<str name ="pa">5678</str>
<str name ="et">Title 2</str>
<str name ="pb">Publisher 2</str>
<str name ="ur">http://www.exampletwo.com</str>
</doc></result></response>'''
tree = ET.fromstring(resp)
for pan in tree.findall('.//str[@name="pa"]'):
print(pan.text)
코드를 사용하려면 약간의 변경이 필요합니다.
어느 한 쪽:
for doc in tree[1].findall("doc"):
pan = doc.find('str[@name="pa"]').text
print (pan)
또는
for doc in tree.findall(".//doc"):
pan = doc.find('str[@name="pa"]').text
print (pan)
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다