2017-07-07 74 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