1

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.

vvvvv
  • 25,404
  • 19
  • 49
  • 81
Axiom
  • 902
  • 1
  • 10
  • 23

1 Answers1

1

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)

msturdy
  • 10,479
  • 11
  • 41
  • 52
  • This doesn't seem to work. I get an import error. 'from BeautifulSoup import BeautifulSoup ImportError: No module named BeautifulSoup' I use Python 2.7 btw. – Axiom Jan 13 '14 at 12:07
  • Check out the download page, you need to download and install the module... http://www.crummy.com/software/BeautifulSoup/#Download – msturdy Jan 13 '14 at 12:09
  • Yeah, I know that much. I just tried to uninstall/re-install it. Still same error. – Axiom Jan 13 '14 at 12:20
  • **wait** I got it. Thank you for the help :) I had to install BS3 instead of BS4. My mistake. – Axiom Jan 13 '14 at 12:24
  • ah! I was just checking on possible installation errors! glad it helped ;) – msturdy Jan 13 '14 at 12:25
  • Use VirtualEnv to install Python libraries: http://opensourcehacker.com/2012/09/16/recommended-way-for-sudo-free-installation-of-python-software-with-virtualenv/ – Mikko Ohtamaa Jan 21 '14 at 07:35