Search code examples
pythonxmlbotsskypeskype4py

Easiest way to sort XML in Python? [Skype Bot]


I'm making a Skype bot and one of my commands is !trace ip_or_website_here

However, I see to be having an issue sorting out my XML Responses.

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)

And my functions.py:

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

Now, my issue is that responses look like this:

!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>

Now, I want to be able to make it work without having the XML Tags.

More like this:
IP Address: ip
Country Code: CountryCodeHere
Country Name: countrynamehere
and so on.

Any help would be appreciated.


Solution

  • BeautifulSoup is good for parsing 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'
    

    Or in more detail..

    #!/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
    

    Output:

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

    (updated to latest BeautifulSoup version)