• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python http.get_xml函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: bam

def bam(inp):
    ".bam [basic|magic|pepsi|jprdy] <message> -- creates a big ass message"

    host = 'http://bigassmessage.com/'
    path = 'dsx_BAM/boe.php?'
    params = {'action': 'saveMsg', 'theStyle': 'basic', 'theMessage': inp}

    if ' ' in inp:
        style, message = inp.split(None, 1)
        if style in ['basic', 'magic', 'pepsi', 'jprdy']:
            params['theStyle'] = style
            params['theMessage'] = message

    response = http.get_xml(host + path, params)
    status = response.xpath('//status/text()')[0]
    if status == 'ok':
        return host + response.xpath('//msgid/text()')[0]
    else:
        return response.xpath('//message/text()')[0]
开发者ID:Ipsum,项目名称:skybot,代码行数:19,代码来源:bigassmessage.py


示例17: bam

def bam(inp):
    ".bam [basic|magic|heart|krugr] <message> -- creates a big ass message"
    
    host = 'http://bigassmessage.com/'
    path = 'BAM.php?'
    params = {'action': 'SAVE', 'theStyle': 'basic', 'theMessage': inp}
    
    if ' ' in inp:
        style, message = inp.split(None, 1)
        if style in ['basic', 'magic', 'heart', 'krugr']:
            params['theStyle'] = style
            params['theMessage'] = message
    
    response = http.get_xml(host + path, params)
    status = response.xpath('//status/text()')[0]
    
    if status == 'ok':
        return host + response.xpath('//msgid/text()')[0]
    else:
        return response.xpath('//message/text()')[0]
开发者ID:avidal,项目名称:skybot,代码行数:20,代码来源:bigassmessage.py


示例18: wa

def wa(inp, api_key=None):
    """.wa/.calc <query> - Computes <query> using Wolfram Alpha."""

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

    try:
        result = http.get_xml(url, input=inp, appid=api_key)
    except:
        return "WolframAlpha query timed out for '%s'" % inp

    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 not ret:
        return 'No results'

    return text.truncate_str(ret.split('. ')[0], 230)
开发者ID:Cameri,项目名称:Gary,代码行数:41,代码来源:wolframalpha.py


示例19: stock

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

    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 not "company" in results:
        guess_data = json.loads(http.get("http://d.yimg.com/autoc.finance.yahoo.com/autoc", query=inp,
                                         callback="YAHOO.Finance.SymbolSuggest.ssCallback")[39:-1])
        guess = guess_data['ResultSet']['Result']
        if len(guess) > 0:
            guess = guess[0]["symbol"]
            return stock(guess)
        else:
            return "error: unable to get stock info for '{}'".format(inp)

    if results['last'] == '0.00':
        return "%(company)s - last known stock value was 0.00 %(currency)s" \
               " as of %(trade_timestamp)s" % results

    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:thejordan95,项目名称:Groovebot2,代码行数:40,代码来源:stock.py


示例20: weather

def weather(inp, nick='', server='', reply=None, db=None, notice=None):
    ".weather <location> [dontsave] -- Gets weather data"\
    " for <location> from Google."
    loc = inp

    dontsave = loc.endswith(" dontsave")
    if dontsave:
        loc = loc[:-9].strip().lower()

    db.execute("create table if not exists weather(nick primary key, loc)")

    if not loc:
        loc = db.execute("select loc from weather where nick=lower(?)",
                            (nick,)).fetchone()
        if not loc:
            notice(weather.__doc__)
            return
        loc = loc[0]

    w = http.get_xml('http://www.google.com/ig/api', weather=loc)
    w = w.find('weather')

    if w.find('problem_cause') is not None:
        notice("Couldn't fetch weather data for '%s', try using a zip or " \
                "postal code." % inp)
        return

    info = dict((e.tag, e.get('data')) for e in w.find('current_conditions'))
    info['city'] = w.find('forecast_information/city').get('data')
    info['high'] = w.find('forecast_conditions/high').get('data')
    info['low'] = w.find('forecast_conditions/low').get('data')

    reply('%(city)s: %(condition)s, %(temp_f)sF/%(temp_c)sC (H:%(high)sF'\
            ', L:%(low)sF), %(humidity)s, %(wind_condition)s.' % info)

    if inp and not dontsave:
        db.execute("insert or replace into weather(nick, loc) values (?,?)",
                     (nick.lower(), loc))
        db.commit()
开发者ID:ShadowDev,项目名称:CloudBot,代码行数:39,代码来源:weather.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python http.quote_plus函数代码示例发布时间:2022-05-26
下一篇:
Python http.get_soup函数代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap