Using urllib and minidom to fetch XML data
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 min开发者_如何学Cidom 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?
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)
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())
Try this:
f = urllib.urlopen(xmlpath)
html = f.read()
xmldoc = minidom.parse(html)
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.
精彩评论