2017-07-07 77 views
0

有什麼不對下面的代碼?我期待布吉作爲輸出。Python的命名空間中的XML的解析錯誤

import urllib.request 
from html.parser import HTMLParser 
import xml.etree.ElementTree as ET 

html = '''<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" 
xmlns="http://purl.org/rss/1.0/" 
xmlns:enc="http://purl.oclc.org/net/rss_2.0/enc#" 
><foo><title>boogie</title></foo></rdf:RDF>''' 

root = ET.fromstring(html) 
ns = { 'default': 'http://purl.org/rss/1.0/', 'rdf': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'} 

titles = root.findall("default:.//title", ns) 
[print(title.text) for title in titles] 

回答

1
import urllib.request 
from html.parser import HTMLParser 
import xml.etree.ElementTree as ET 

html = '''<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" 
xmlns="http://purl.org/rss/1.0/" 
xmlns:enc="http://purl.oclc.org/net/rss_2.0/enc#" 
><foo><title>boogie</title></foo></rdf:RDF>''' 

root = ET.fromstring(html) 
ns = '{http://purl.org/rss/1.0/}' 

titles = root.findall(".//%stitle" % ns) 
print titles[0].text 

這是工作版本

+0

但兩種語法應該工作。 – user3210796

+0

你可以改變這一行:'標題= root.findall( 「默認:.//標題」,NS)' 到'標題= root.findall( 「.//默認:標題」,NS)'然後它會工作。你把'default'放在錯誤的地方 – gaback