问题
I'm trying to fetch data from a XML service... this one.
http://xmlweather.vedur.is/?op_w=xml&type=forec&lang=is&view=xml&ids=1
I'm using urrlib and minidom and i can't seem to make it work. I've used minidom with files and not url.
This is the code im trying to use
xmlurl = 'http://xmlweather.vedur.is'
xmlpath = xmlurl + '?op_w=xml&type=forec&lang=is&view=xml&ids=' + str(location)
xmldoc = minidom.parse(urllib.urlopen(xmlpath))
Can anyone help me?
回答1:
The following should work (or at least give you a strong idea about what is going wrong):
from xml.dom.minidom import parse
import urllib
xmlurl = 'http://xmlweather.vedur.is'
xmlpath = xmlurl + '?op_w=xml&type=forec&lang=is&view=xml&ids=' + str(location)
try:
xml = urllib.urlopen(xmlpath)
dom = parse(xml)
except e as Exception:
print(e)
回答2:
The parse() is looking for a file and you're giving it a string. There is another class called parsestring()
try:
from xml.dom.minidom import parseString
import urllib2
xml = urllib2.urlopen(xmlpath)
dom = parseString(xml.read())
回答3:
Try this:
f = urllib.urlopen(xmlpath)
html = f.read()
xmldoc = minidom.parse(html)
回答4:
I've just been doing something similar, and came across your question.
In my case, I thought that minidom.parse was broken because I was getting syntax errors. It turns out the syntax errors were in my xml document though - the trace didn't make that very clear.
If you're getting syntax errors with minidom.parse or minidom.parseString, make sure to check your source file.
来源:https://stackoverflow.com/questions/3351853/using-urllib-and-minidom-to-fetch-xml-data