使用Python访问在线XML

0 投票
1 回答
2562 浏览
提问于 2025-04-17 21:14

我想从网上获取一个xml文件(其实有很多个)。我之前有一段代码可以做到这一点,但我重新安装了操作系统,结果忘了备份我的Python脚本,真是太糟糕了 :(

我现在就是想访问这个xml文件,一旦拿到数据,我记得怎么处理这些数据。我就是想不起来怎么去访问它。我到处找资料,发现的都是关于urllib的内容,但当我尝试发请求的时候,脚本因为网址里的':'符号而无法运行。有没有人能帮帮我??

这是我想访问的其中一个xml地址: http://api.eve-central.com/api/marketstat?typeid=34&regionlimit=10000002

1 个回答

3

你需要的就是urllib2这个库。

http://docs.python.org/2/howto/urllib2.html

简单来说,这就是它的使用方法:

url_response = urllib2.urlopen(url) ## return a http.response object 
xml_content = url_response.read() ## read the content 

另外,我还使用beautifulsoup4来从xml文档中提取数据,具体可以查看这个链接 http://www.crummy.com/software/BeautifulSoup/bs4/doc/

简单来说:

from bs4 import BeautifulSoup           ## import bs4 as BeautifulSoup
content = BeautifulSoup(xml_content)    ## convert xml content to beautifulsoup object 
span = content.find_all("span")         ## find all span tag and return as list

加油!

撰写回答