1

私は Skype ボットを作成しており、私のコマンドの 1 つは!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 に答える