Using urllib and minidom to fetch XML data

旧时模样 提交于 2019-12-08 09:18:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!