python - 在 Python 中对 XML 进行排序的最简单方法? [Skype 机器人]

标签 python xml bots skype skype4py

我正在制作一个 Skype 机器人,我的命令之一是 !trace ip_or_website_here

但是,我发现整理 XML 响应时遇到问题。

Commands.py:

elif msg.startswith('!trace '):
    debug.action('!trace command executed.')
    send(self.nick + 'Tracing IP. Please Wait...')
    ip = msg.replace('!trace ', '', 1);
    ipinfo = functions.traceIP(ip)
    send('IP Information:\n'+ipinfo)

还有我的functions.py:

def traceIP(ip):
    return urllib2.urlopen('http://freegeoip.net/xml/'+ip).read()

现在,我的问题是响应如下所示:

!trace skype.com
Bot: Tracing IP. Please Wait...
IP Information:
<?xml version="1.0" encoding="UTF-8"?>
<Response>
<Ip>91.190.216.21</Ip>
<CountryCode>LU</CountryCode>
<CountryName>Luxembourg</CountryName>
<RegionCode></RegionCode>
<RegionName></RegionName>
<City></City>
<ZipCode></ZipCode>
<Latitude>49.75</Latitude>
<Longitude>6.1667</Longitude>
<MetroCode></MetroCode>
<AreaCode></AreaCode>

现在,我希望能够在没有 XML 标签的情况下使其工作。

更多类似这样的:
IP地址:ip
国家/地区代码:国家/地区代码此处
国家/地区名称:countrynamehere
等等。

如有任何帮助,我们将不胜感激。

最佳答案

BeautifulSoup有利于解析 XML。

>>> from bs4 import BeautifulSoup
>>> xml = urllib2.urlopen('http://freegeoip.net/xml/192.168.1.1').read()
>>> soup = BeautifulSoup(xml)
>>> soup.ip.text
u'192.168.1.1'

或者更详细..

#!/usr/bin/env python
import urllib2
from bs4 import BeautifulSoup

ip  = "192.168.1.1"

xml = urllib2.urlopen('http://freegeoip.net/xml/' + ip).read()

soup = BeautifulSoup(xml)

print "IP Address: %s" % soup.ip.text
print "Country Code: %s" % soup.countrycode.text
print "Country Name: %s" % soup.countryname.text

输出:

IP Address: 192.168.1.1
Country Code: RD
Country Name: Reserved

(已更新至最新 BeautifulSoup 版本)

关于python - 在 Python 中对 XML 进行排序的最简单方法? [Skype 机器人],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21090095/

相关文章:

python - 从 UTC 偏移获取时区缩写

ruby - Ruby/Rails 中的人工智能或机器人

azure - Azure 中的 Microsoft Bot 是否需要任何特定权限才能在表存储中写入?

python - 客户端脚本在UDP套接字上停止时获取ConnectionResetError

python - 无法在 Ubuntu 中安装正则表达式

java - 如何在java中动态创建XML元素?

xml - Spring MVC @ResponseBody 返回一个 Map 产生 "Error 406 NOT ACCEPTABLE"

javascript - 我的 Discord.js 机器人正在运行(在线并显示在控制台中),但它不会响应命令

python - pylab.show() "QCoreApplication::exec: The event loop is already running"

sql - 替换存储在 SQL Server 数据库列中的 XML 中的节点名称