Using urllib and minidom to fetch XML data

2019-06-13 16:58发布

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?

4条回答
迷人小祖宗
2楼-- · 2019-06-13 17:24

Try this:

f = urllib.urlopen(xmlpath)
html = f.read()
xmldoc = minidom.parse(html)
查看更多
祖国的老花朵
3楼-- · 2019-06-13 17:31

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())
查看更多
一夜七次
4楼-- · 2019-06-13 17:34

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)
查看更多
三岁会撩人
5楼-- · 2019-06-13 17:38

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.

查看更多
登录 后发表回答