当前位置: 首页>>代码示例>>Python>>正文


Python http.get_xml函数代码示例

本文整理汇总了Python中util.http.get_xml函数的典型用法代码示例。如果您正苦于以下问题:Python get_xml函数的具体用法?Python get_xml怎么用?Python get_xml使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了get_xml函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: get_episodes_for_series

def get_episodes_for_series(seriesname):
    res = {"error": None, "ended": False, "episodes": None, "name": None}
    # http://thetvdb.com/wiki/index.php/API:GetSeries
    try:
        query = http.get_xml(base_url + "GetSeries.php", seriesname=seriesname)
    except http.URLError:
        res["error"] = "error contacting thetvdb.com"
        return res

    series_id = query.xpath("//seriesid/text()")

    if not series_id:
        res["error"] = "unknown tv series (using www.thetvdb.com)"
        return res

    series_id = series_id[0]

    try:
        series = http.get_xml(base_url + "%s/series/%s/all/en.xml" % (api_key, series_id))
    except http.URLError:
        res["error"] = "error contacting thetvdb.com"
        return res

    series_name = series.xpath("//SeriesName/text()")[0]

    if series.xpath("//Status/text()")[0] == "Ended":
        res["ended"] = True

    res["episodes"] = series.xpath("//Episode")
    res["name"] = series_name
    return res
开发者ID:retrogradeorbit,项目名称:skybot,代码行数:31,代码来源:tvdb.py

示例2: get_episodes_for_series

def get_episodes_for_series(seriesname, api_key):
    res = {"error": None, "ended": False, "episodes": None, "name": None}
    # http://thetvdb.com/wiki/index.php/API:GetSeries
    try:
        query = http.get_xml(base_url + 'GetSeries.php', seriesname=seriesname)
    except URLError:
        res["error"] = "error contacting thetvdb.com"
        return res

    series_id = query.xpath('//seriesid/text()')

    if not series_id:
        res["error"] = "unknown tv series (using www.thetvdb.com)"
        return res

    series_id = series_id[0]

    try:
        series = get_zipped_xml(base_url + '%s/series/%s/all/en.zip' %
                                    (api_key, series_id), path="en.xml")
    except URLError:
        res["error"] = "error contacting thetvdb.com"
        return res

    series_name = series.xpath('//SeriesName/text()')[0]

    if series.xpath('//Status/text()')[0] == 'Ended':
        res["ended"] = True

    res["episodes"] = series.xpath('//Episode')
    res["name"] = series_name
    return res
开发者ID:ShadowDev,项目名称:CloudBot,代码行数:32,代码来源:tvdb.py

示例3: wiki

def wiki(inp):
    '''.w/.wiki <phrase> -- gets first sentence of wikipedia ''' \
        '''article on <phrase>'''

    x = http.get_xml(search_url, search=inp)

    ns = '{http://opensearch.org/searchsuggest2}'
    items = x.findall(ns + 'Section/' + ns + 'Item')

    if items == []:
        if x.find('error') is not None:
            return 'error: %(code)s: %(info)s' % x.find('error').attrib
        else:
            return 'no results found'

    def extract(item):
        return [item.find(ns + x).text for x in
                ('Text', 'Description', 'Url')]

    title, desc, url = extract(items[0])

    if 'may refer to' in desc:
        title, desc, url = extract(items[1])

    title = paren_re.sub('', title)

    if title.lower() not in desc.lower():
        desc = title + desc

    desc = re.sub('\s+', ' ', desc).strip()  # remove excess spaces

    if len(desc) > 300:
        desc = desc[:300] + '...'

    return '%s -- %s' % (desc, http.quote(http.unquote(url), ':/'))
开发者ID:whoflungpoop,项目名称:badbot,代码行数:35,代码来源:wikipedia.py

示例4: kb

def kb(inp):
    """kb <topic> -- Gets the first article available on <topic>."""

    x = http.get_xml(search_url, search=inp)

    ns = '{http://opensearch.org/searchsuggest2}'
    items = x.findall(ns + 'Section/' + ns + 'Item')

    if not items:
        if x.find('error') is not None:
            return 'error: %(code)s: %(info)s' % x.find('error').attrib
        else:
            return 'No results found.'

    def extract(item):
        return [item.find(ns + x).text for x in
                ('Text', 'Description', 'Url')]

    title, desc, url = extract(items[0])

    if 'may refer to' in desc:
        title, desc, url = extract(items[1])

    title = paren_re.sub('', title)

    if title.lower() not in desc.lower():
        desc = title + desc

    desc = u' '.join(desc.split())  # remove excess spaces

    desc = text.truncate_str(desc, 200)

    return u'{} :: {}'.format(desc, http.quote(url, ':/'))
开发者ID:FurCode,项目名称:TechsupportModules,代码行数:33,代码来源:knowledgebase.py

示例5: get_series_info

def get_series_info(seriesname):
    res = {"error": None, "ended": False, "episodes": None, "name": None}
    # http://thetvdb.com/wiki/index.php/API:GetSeries
    try:
        query = http.get_xml(base_url + 'GetSeries.php', seriesname=seriesname)
    except URLError:
        res["error"] = "error contacting thetvdb.com"
        return res
    series_id = ""
    try: series_id = query.xpath('//id/text()')
    except: print "Failed"


    if not series_id:
        result = "\x02Could not find show:\x02 %s" % seriesname
    else:
        series_name = query.xpath('//SeriesName/text()')[0]
        overview = query.xpath('//Overview/text()')[0]
        firstaired = query.xpath('//FirstAired/text()')[0]
        #imdb_id = query.xpath('//IMDB_ID/text()')[0]
        #imdb_url = web.isgd("http://www.imdb.com/title/%s" % imdb_id)
        tvdb_url = web.isgd("http://thetvdb.com/?tab=series&id=%s" % series_id[0])
        status = tv_next(seriesname)
        result = '\x02%s\x02 (%s) \x02-\x02 \x02%s\x02 - [%s] - %s' % (series_name, firstaired, status, tvdb_url, overview)

    return result
开发者ID:inexist3nce,项目名称:Taigabot,代码行数:26,代码来源:media.py

示例6: stock

def stock(inp):
    ".stock <symbol> -- Gets information about stock symbol <symbol>."

    url = 'http://www.google.com/ig/api?stock=%s'

    parsed = http.get_xml(url, stock=inp)

    if len(parsed) != 1:
        return "error getting stock info"

    # Stuff the results in a dict for easy string formatting
    results = dict((el.tag, el.attrib['data'])
                   for el in parsed.xpath('//finance/*'))

    # if we dont get a company name back, the symbol doesn't match a company
    if results['company'] == '':
        return "unknown ticker symbol %s" % inp

    if results['change'][0] == '-':
        results['color'] = "5"
    else:
        results['color'] = "3"

    ret = "%(company)s - %(last)s %(currency)s "                   \
          "\x03%(color)s%(change)s (%(perc_change)s)\x03 "        \
          "as of %(trade_timestamp)s" % results

    if results['delay'] != '0':
        ret += " (delayed %s minutes)" % results['delay']

    return ret
开发者ID:frozenMC,项目名称:CloudBot,代码行数:31,代码来源:stock.py

示例7: wiki

def wiki(inp):
    "wiki <phrase> -- Gets first sentence of Wikipedia article on <phrase>."

    x = http.get_xml(search_url, search=inp)

    ns = '{http://opensearch.org/searchsuggest2}'
    items = x.findall(ns + 'Section/' + ns + 'Item')

    if items == []:
        if x.find('error') is not None:
            return 'error: %(code)s: %(info)s' % x.find('error').attrib
        else:
            return 'No results found.'

    def extract(item):
        return [item.find(ns + x).text for x in
                            ('Text', 'Description', 'Url')]

    title, desc, url = extract(items[0])

    if 'may refer to' in desc:
        title, desc, url = extract(items[1])

    title = paren_re.sub('', title)

    if title.lower() not in desc.lower():
        desc = title + desc

    desc = re.sub('\s+', ' ', desc).strip()  # remove excess spaces

    desc = text.truncate_str(desc, 250)

    return '%s -- %s' % (desc, http.quote(url, ':/'))
开发者ID:Juboo,项目名称:UguuBot,代码行数:33,代码来源:wikipedia.py

示例8: time_command

def time_command(inp, bot=None):
    """.time <area> - Gets the time in <area>."""

    if inp.lower() == "butts":
        return "It's always time for butts."

    query = "current time in {}".format(inp)

    api_key = bot.config.get("api_keys", {}).get("wolframalpha", None)
    if not api_key:
        return "error: no wolfram alpha api key set"

    request = http.get_xml(api_url, input=query, appid=api_key)
    time = " ".join(
        request.xpath("//pod[@title='Result']/subpod/plaintext/text()"))
    time = time.replace("  |  ", ", ")

    if time:
        # nice place name for UNIX time
        if inp.lower() == "unix":
            place = "Unix Epoch"
        else:
            place = cap_first(
                " ".join(request.xpath("//pod[@" "title='Input interpretation']/subpod/plaintext/text()")).split('|')[0])
            place = place.replace("Current Time In", "").strip()
        return "\x02{}\x02 - {}".format(place, time)
    else:
        return "Could not get the time for '{}'.".format(inp)
开发者ID:Cameri,项目名称:Gary,代码行数:28,代码来源:time.py

示例9: get_twitter

def get_twitter(inp):
    try:
        text = 'status/text'
        url = 'http://twitter.com/users/show/%s.xml' % inp
        screen_name = 'screen_name'
        tweet = http.get_xml(url)
        text = unescape_xml(tweet.find(text).text.replace('\n', ''))
        screen_name = tweet.find(screen_name).text
    except http.HTTPError, e:
        return 'error: '+str(e.code)
开发者ID:Red-M,项目名称:frogbot,代码行数:10,代码来源:atwitter.py

示例10: wolframalpha

def wolframalpha(inp, bot=None):
    "wa <query> -- Computes <query> using Wolfram Alpha."

    api_key = bot.config.get("api_keys", {}).get("wolframalpha", None)

    if not api_key:
        return "error: missing api key"

    url = 'http://api.wolframalpha.com/v2/query?format=plaintext'

    result = http.get_xml(url, input=inp, appid=api_key)

    # get the URL for a user to view this query in a browser
    query_url = "http://www.wolframalpha.com/input/?i=" + \
                http.quote_plus(inp.encode('utf-8'))
    try:
        short_url = web.isgd(query_url)
    except (web.ShortenError, http.HTTPError):
        short_url = query_url

    pod_texts = []
    for pod in result.xpath("//pod[@primary='true']"):
        title = pod.attrib['title']
        if pod.attrib['id'] == 'Input':
            continue

        results = []
        for subpod in pod.xpath('subpod/plaintext/text()'):
            subpod = subpod.strip().replace('\\n', '; ')
            subpod = re.sub(r'\s+', ' ', subpod)
            if subpod:
                results.append(subpod)
        if results:
            pod_texts.append(title + ': ' + ', '.join(results))

    ret = ' - '.join(pod_texts)

    if not pod_texts:
        return 'No results.'

    ret = re.sub(r'\\(.)', r'\1', ret)

    def unicode_sub(match):
        return unichr(int(match.group(1), 16))

    ret = re.sub(r'\\:([0-9a-z]{4})', unicode_sub, ret)

    ret = text.truncate_str(ret, 250)

    if not ret:
        return 'No results.'

    return "%s - %s" % (ret, short_url)
开发者ID:Juboo,项目名称:UguuBot,代码行数:53,代码来源:wolframalpha.py

示例11: getTwitchStream

def getTwitchStream(user):
    r = http.get_xml('http://api.justin.tv/api/stream/list.xml?channel=%s' % user)
    try:
        viewers = r.xpath('//stream/channel_count/text()')[0]
    except IndexError:
        return False
    if r.xpath('//stream/format/text()')[0] == 'live':
        if viewers:
            return True, viewers
        else:
            return False
    else:
        return False
开发者ID:limnick,项目名称:siri,代码行数:13,代码来源:streams.py

示例12: getOwnedStream

def getOwnedStream(user):
    h = http.get_xml('http://api.own3d.tv/liveCheck.php?live_id=' + user)
    status = h.xpath('//liveEvent/isLive/text()')[0]
    try:
        viewers = h.xpath('//liveEvent/liveViewers/text()')[0]
    except IndexError:
        return False
    if status == 'true':
        if viewers:
            return True, viewers
        else:
            return False
    else:
        return False
开发者ID:limnick,项目名称:siri,代码行数:14,代码来源:streams.py

示例13: wolframalpha

def wolframalpha(inp, bot=None, input=None):
    ".wa <query> -- Computes <query> using Wolfram Alpha."

    api_key = bot.config.get("api_keys", {}).get("wolframalpha", None)
    if api_key is None:
        return "error: no api key set"
    if '^' in input.paraml[1]:
        inp = str(inp).replace("^", bot.chanseen[input.conn.server][input.chan][0])
    url = 'http://api.wolframalpha.com/v2/query?format=plaintext'

    result = http.get_xml(url, input=inp, appid=api_key)
    input.say("Please wait.")
    pod_texts = []
    for pod in result.xpath("//pod"):
        title = pod.attrib['title']
        if pod.attrib['id'] == 'Input':
            continue

        results = []
        for subpod in pod.xpath('subpod/plaintext/text()'):
            subpod = subpod.strip().replace('\\n', '; ')
            subpod = re.sub(r'\s+', ' ', subpod)
            if subpod:
                results.append(subpod)
        if results:
            pod_texts.append(title + ': ' + '|'.join(results))

    ret = '. '.join(pod_texts)

    if not pod_texts:
        return 'No results.'

    ret = re.sub(r'\\(.)', r'\1', ret)

    def unicode_sub(match):
        return unichr(int(match.group(1), 16))

    ret = re.sub(r'\\:([0-9a-z]{4})', unicode_sub, ret)

    if len(ret) > 430:
        ret = ret[:ret.rfind(' ', 0, 430)]
        ret = re.sub(r'\W+$', '', ret) + '...'

    if not ret:
        return 'No results..'

    return ret
开发者ID:Red-M,项目名称:frogbot,代码行数:47,代码来源:wolframalpha.py

示例14: wolframalpha

def wolframalpha(inp, bot=None):
    ".wa/.wolframalpha <query> -- computes <query> using Wolfram Alpha"

    api_key = "22PK5Q-Y7YKV77E4U"
    #api_key = bot.config.get("api_keys", {}).get("wolframalpha", None)
    #if api_key is None:
    #    return "error: no api key set"

    url = 'http://api.wolframalpha.com/v2/query?format=plaintext'

    result = http.get_xml(url, input=inp, appid=api_key)

    pod_texts = []
    for pod in result.xpath("//pod"):
        title = pod.attrib['title']
        if pod.attrib['id'] == 'Input':
            continue

        results = []
        for subpod in pod.xpath('subpod/plaintext/text()'):
            subpod = subpod.strip().replace('\\n', '; ')
            subpod = re.sub(r'\s+', ' ', subpod)
            if subpod:
                results.append(subpod)
        if results:
            pod_texts.append(title + ': ' + '|'.join(results))

    ret = '. '.join(pod_texts)

    if not pod_texts:
        return 'no results'

    ret = re.sub(r'\\(.)', r'\1', ret)

    def unicode_sub(match):
        return unichr(int(match.group(1), 16))

    ret = re.sub(r'\\:([0-9a-z]{4})', unicode_sub, ret)

    if len(ret) > 430:
        ret = ret[:ret.rfind(' ', 0, 430)]
        ret = re.sub(r'\W+$', '', ret) + '...'

    if not ret:
        return 'no results'

    return ret
开发者ID:limnick,项目名称:siri,代码行数:47,代码来源:wolframalpha.py

示例15: wolframalpha

def wolframalpha(inp, bot=None):
    ".wa <query> -- Computes <query> using Wolfram Alpha."
    api_key = bot.config.get("api", {}).get("wolframalpha")
    if api_key is None:
        return "I have a lazy owner, they won't even bother adding an API key! " + randout.fail() 

    url = 'http://api.wolframalpha.com/v2/query?format=plaintext'

    result = http.get_xml(url, input=inp, appid=api_key)
    fail = 'No results. ' + randout.fail()

    pod_texts = []
    for pod in result.xpath("//pod"):
        title = pod.attrib['title']
        if pod.attrib['id'] == 'Input':
            continue

        results = []
        for subpod in pod.xpath('subpod/plaintext/text()'):
            subpod = subpod.strip().replace('\\n', '; ')
            subpod = re.sub(r'\s+', ' ', subpod)
            if subpod:
                results.append(subpod)
        if results:
            pod_texts.append(title + ': ' + '|'.join(results))

    ret = '. '.join(pod_texts)

    if not pod_texts:
        return fail

    ret = re.sub(r'\\(.)', r'\1', ret)

    def unicode_sub(match):
        return unichr(int(match.group(1), 16))

    ret = re.sub(r'\\:([0-9a-z]{4})', unicode_sub, ret)

    if len(ret) > 430:
        ret = ret[:ret.rfind(' ', 0, 430)]
        ret = re.sub(r'\W+$', '', ret) + '...'

    if not ret:
        return fail

    return ret
开发者ID:GUIpsp,项目名称:wololo,代码行数:46,代码来源:wolframalpha.py


注:本文中的util.http.get_xml函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。