1

我正在制作一个 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
国家代码:CountryCodeHere
国家名称:countrynamehere
等等。

任何帮助,将不胜感激。

4

1 回答 1

1

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版本)

于 2014-01-13T11:49:12.540 回答