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


Python request.quote方法代码示例

本文整理汇总了Python中urllib.request.quote方法的典型用法代码示例。如果您正苦于以下问题:Python request.quote方法的具体用法?Python request.quote怎么用?Python request.quote使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在urllib.request的用法示例。


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

示例1: google_image

# 需要导入模块: from urllib import request [as 别名]
# 或者: from urllib.request import quote [as 别名]
def google_image(message, keywords):
    """
    google で画像検索した結果を返す

    https://github.com/llimllib/limbo/blob/master/limbo/plugins/image.py
    """

    query = quote(keywords)
    searchurl = "https://www.google.com/search?tbm=isch&q={0}".format(query)

    # this is an old iphone user agent. Seems to make google return good results.
    useragent = "Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Versio  n/4.0.5 Mobile/8A293 Safari/6531.22.7"

    result = requests.get(searchurl, headers={"User-agent": useragent}).text
    images = list(map(unescape, re.findall(r"var u='(.*?)'", result)))

    if images:
        botsend(message, choice(images))
    else:
        botsend(message, "`{}` での検索結果はありませんでした".format(keywords)) 
开发者ID:pyconjp,项目名称:pyconjpbot,代码行数:22,代码来源:google.py

示例2: google_map

# 需要导入模块: from urllib import request [as 别名]
# 或者: from urllib.request import quote [as 别名]
def google_map(message, keywords):
    """
    google マップで検索した結果を返す

    https://github.com/llimllib/limbo/blob/master/limbo/plugins/map.py
    """
    query = quote(keywords)

    # Slack seems to ignore the size param
    #
    # To get google to auto-reasonably-zoom its map, you have to use a marker
    # instead of using a "center" parameter. I found that setting it to tiny
    # and grey makes it the least visible.
    url = "https://maps.googleapis.com/maps/api/staticmap?size=800x400&markers={0}&maptype={1}"
    url = url.format(query, 'roadmap')

    botsend(message, url)
    attachments = [{
        'pretext': '<http://maps.google.com/maps?q={}|大きい地図で見る>'.format(query),
        'mrkdwn_in': ["pretext"],
    }]
    botwebapi(message, attachments) 
开发者ID:pyconjp,项目名称:pyconjpbot,代码行数:24,代码来源:google.py

示例3: rename

# 需要导入模块: from urllib import request [as 别名]
# 或者: from urllib.request import quote [as 别名]
def rename(self, ids, new_name):
        """
        功能:改名
        返回值:dict
        """
        try:
            arg = self.str_arg(ids=ids, new_name=new_name)
            url = self.server + 'boat/renameShip/{ids}/{new_name}/'.format(**arg) + self.get_url_end()
            url = quote(url, safe=";/?:@&=+$,", encoding="utf-8")
            data=self.Mdecompress(url)
            data = json.loads(data)
            error_find(data)
            if is_write and os.path.exists('requestsData'):
                with open('requestsData/rename.json', 'w') as f:
                    f.write(json.dumps(data))
            return data
        except HmError as e:
            print('Rename FAILED! Reason:', e.message)
            raise
        except Exception as Error_information:
            print('Rename FAILED! Reason:', Error_information)
            raise 
开发者ID:ProtectorMoe,项目名称:pc-protector-moe,代码行数:24,代码来源:Function.py

示例4: stockprice

# 需要导入模块: from urllib import request [as 别名]
# 或者: from urllib.request import quote [as 别名]
def stockprice(ticker):
    url = "https://www.google.com/finance?q={0}"
    soup = BeautifulSoup(
        requests.get(url.format(quote(ticker))).text, "html5lib")

    try:
        company, ticker = re.findall(u"^(.+?)\xa0\xa0(.+?)\xa0", soup.text,
                                     re.M)[0]
    except IndexError:
        logging.info("Unable to find stock {0}".format(ticker))
        return ""
    price = soup.select("#price-panel .pr span")[0].text
    change, pct = soup.select("#price-panel .nwp span")[0].text.split()
    time = " ".join(soup.select(".mdata-dis")[0].parent.text.split()[:4])
    pct.strip('()')

    emoji = ":chart_with_upwards_trend:" if change.startswith("+") \
            else ":chart_with_downwards_trend:"

    return "{0} {1} {2}: {3} {4} {5} {6} {7}".format(
        emoji, company, ticker, price, change, pct, time, emoji) 
开发者ID:llimllib,项目名称:limbo,代码行数:23,代码来源:stock.py

示例5: image

# 需要导入模块: from urllib import request [as 别名]
# 或者: from urllib.request import quote [as 别名]
def image(search, unsafe=False):
    """given a search string, return a image URL via google search"""
    searchb = quote(search.encode("utf8"))

    safe = "&safe=" if unsafe else "&safe=active"
    searchurl = "https://www.google.com/search?tbm=isch&q={0}{1}".format(
        searchb, safe)

    # this is an old iphone user agent. Seems to make google return good results.
    useragent = "Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0 like Mac OS X; en-us)" \
        " AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A293 Safari/6531.22.7"

    result = requests.get(searchurl, headers={"User-agent": useragent}).text

    images = list(map(unescape, re.findall(r"imgres[?]imgurl=(.*?)&amp;", result)))
    shuffle(images)

    if images:
        return images[0]
    return "" 
开发者ID:llimllib,项目名称:limbo,代码行数:22,代码来源:image.py

示例6: gif

# 需要导入模块: from urllib import request [as 别名]
# 或者: from urllib.request import quote [as 别名]
def gif(search, unsafe=False):
    """given a search string, return a gif URL via google search"""
    searchb = quote(search.encode("utf8"))

    safe = "&safe=" if unsafe else "&safe=active"
    searchurl = "https://www.google.com/search?tbs=itp:animated&tbm=isch&q={0}{1}" \
        .format(searchb, safe)

    # this is an old iphone user agent. Seems to make google return good results.
    useragent = "Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0 like Mac OS X; en-us)" \
        " AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A293 Safari/6531.22.7"

    result = requests.get(searchurl, headers={"User-agent": useragent}).text

    gifs = list(map(unescape, re.findall(r"imgres[?]imgurl=(.*?)&amp;", result)))
    shuffle(gifs)

    if gifs:
        return gifs[0]
    return "" 
开发者ID:llimllib,项目名称:limbo,代码行数:22,代码来源:gif.py

示例7: getlnglat

# 需要导入模块: from urllib import request [as 别名]
# 或者: from urllib.request import quote [as 别名]
def getlnglat(address):
    """
    获取一个中文地址的经纬度(lat:纬度值,lng:经度值)
    """
    url_base = "http://api.map.baidu.com/geocoder/v2/"
    output = "json"
    ak = "" # 浏览器端密钥
    address = quote(address) # 由于本文地址变量为中文,为防止乱码,先用quote进行编码
    url = url_base + '?' + 'address=' + address  + '&output=' + output + '&ak=' + ak 
    lat = 0.0
    lng = 0.0
    res = requests.get(url)
    temp = json.loads(res.text)
    if temp["status"] == 0:
        lat = temp['result']['location']['lat']
        lng = temp['result']['location']['lng']
    return lat,lng


#用来正常显示中文标签 
开发者ID:ideaOzy,项目名称:data_analysis,代码行数:22,代码来源:gaode_map.py

示例8: search_bing

# 需要导入模块: from urllib import request [as 别名]
# 或者: from urllib.request import quote [as 别名]
def search_bing(query):
        """
        通过bing检索答案,包括bing知识图谱、bing网典
        :param query:
        :return: list, string
        """
        answer = []
        left_text = ''
        # 获取bing的摘要
        soup_bing = html_crawler.get_html_bing(bing_url_prefix + quote(query))
        # 判断是否在Bing的知识图谱中
        r = soup_bing.find(class_="bm_box")

        if r:
            r = r.find_all(class_="b_vList")
            if r and len(r) > 1:
                r = r[1].find("li").get_text().strip()
                if r:
                    answer.append(r)
                    logger.debug("Bing知识图谱找到答案")
                    return answer, left_text
        else:
            r = soup_bing.find(id="b_results")
            if r:
                bing_list = r.find_all('li')
                for bl in bing_list:
                    temp = bl.get_text()
                    if temp.__contains__(" - 必应网典"):
                        logger.debug("查找Bing网典")
                        url = bl.find("h2").find("a")['href']
                        if url:
                            bingwd_soup = html_crawler.get_html_bingwd(url)
                            r = bingwd_soup.find(class_='bk_card_desc').find("p")
                            if r:
                                r = r.get_text().replace("\n", "").strip()
                                if r:
                                    logger.debug("Bing网典找到答案")
                                    answer.append(r)
                                    return answer, left_text
                left_text += r.get_text()
        return answer, left_text 
开发者ID:shibing624,项目名称:dialogbot,代码行数:43,代码来源:search_engine.py

示例9: google

# 需要导入模块: from urllib import request [as 别名]
# 或者: from urllib.request import quote [as 别名]
def google(message, keywords):
    """
    google で検索した結果を返す

    https://github.com/llimllib/limbo/blob/master/limbo/plugins/google.py
    """

    if keywords == 'help':
        return

    query = quote(keywords)
    url = "https://encrypted.google.com/search?q={0}".format(query)
    soup = BeautifulSoup(requests.get(url).text, "html.parser")

    answer = soup.findAll("h3", attrs={"class": "r"})
    if not answer:
        botsend(message, "`{}` での検索結果はありませんでした".format(keywords))

    try:
        _, url = answer[0].a['href'].split('=', 1)
        url, _ = url.split('&', 1)
        botsend(message, unquote(url))
    except IndexError:
        # in this case there is a first answer without a link, which is a
        # google response! Let's grab it and display it to the user.
        return ' '.join(answer[0].stripped_strings) 
开发者ID:pyconjp,项目名称:pyconjpbot,代码行数:28,代码来源:google.py

示例10: google

# 需要导入模块: from urllib import request [as 别名]
# 或者: from urllib.request import quote [as 别名]
def google(q):
    query = quote(q)
    url = "https://encrypted.google.com/search?q={0}".format(query)
    soup = BeautifulSoup(requests.get(url).text, "html5lib")

    answer = soup.findAll("h3", attrs={"class": "r"})
    if not answer:
        return ":crying_cat_face: Sorry, google doesn't have an answer for you :crying_cat_face:"

    try:
        return unquote(re.findall(r"q=(.*?)&", str(answer[0]))[0])
    except IndexError:
        # in this case there is a first answer without a link, which is a
        # google response! Let's grab it and display it to the user.
        return ' '.join(answer[0].stripped_strings) 
开发者ID:llimllib,项目名称:limbo,代码行数:17,代码来源:google.py

示例11: youtube

# 需要导入模块: from urllib import request [as 别名]
# 或者: from urllib.request import quote [as 别名]
def youtube(searchterm):
    url = "https://www.youtube.com/results?search_query={0}"
    url = url.format(quote(searchterm))

    r = requests.get(url)
    results = re.findall('a href="(/watch[^&]*?)"', r.text)

    if not results:
        return "sorry, no videos found"

    return "https://www.youtube.com{0}".format(results[0]) 
开发者ID:llimllib,项目名称:limbo,代码行数:13,代码来源:youtube.py

示例12: calc

# 需要导入模块: from urllib import request [as 别名]
# 或者: from urllib.request import quote [as 别名]
def calc(eq):
    query = quote(eq)
    url = "https://encrypted.google.com/search?hl=en&q={0}".format(query)
    soup = BeautifulSoup(requests.get(url).text, "html5lib")

    answer = soup.findAll("h2", attrs={"class": "r"})
    if not answer:
        answer = soup.findAll("span", attrs={"class": "_m3b"})
        if not answer:
            return ":crying_cat_face: Sorry, google doesn't have an answer for you :crying_cat_face:"

    # They seem to use u\xa0 (non-breaking space) in place of a comma
    answer = answer[0].text.replace(u"\xa0", ",")
    return answer 
开发者ID:llimllib,项目名称:limbo,代码行数:16,代码来源:calc.py

示例13: makemap

# 需要导入模块: from urllib import request [as 别名]
# 或者: from urllib.request import quote [as 别名]
def makemap(query):
    querywords = []
    args = {
        "maptype": "roadmap",
    }
    for word in query.split(" "):
        if '=' in word:
            opt, val = word.split("=")
            args[opt] = val
        else:
            querywords.append(word)

    query = quote(" ".join(querywords).encode("utf8"))

    # Slack seems to ignore the size param
    #
    # To get google to auto-reasonably-zoom its map, you have to use a marker
    # instead of using a "center" parameter. I found that setting it to tiny
    # and grey makes it the least visible.
    url = "https://maps.googleapis.com/maps/api/staticmap?size=800x400&markers=size:tiny%7Ccolor:0xAAAAAA%7C{0}&maptype={1}"
    url = url.format(query, args["maptype"])

    if "zoom" in args:
        url += "&zoom={0}".format(args["zoom"])

    return url 
开发者ID:llimllib,项目名称:limbo,代码行数:28,代码来源:map.py

示例14: gif

# 需要导入模块: from urllib import request [as 别名]
# 或者: from urllib.request import quote [as 别名]
def gif(searchterm):
    searchterm = quote(searchterm)
    searchurl = "https://gifcities.archive.org/api/v1/gifsearch?q={}".format(
        searchterm)
    results = requests.get(searchurl).json()
    gifs = list(
        map(lambda x: "https://web.archive.org/web/{0}".format(x['gif']),
            results))
    shuffle(gifs)

    if gifs:
        return gifs[0]
    else:
        return "" 
开发者ID:llimllib,项目名称:limbo,代码行数:16,代码来源:geocities.py

示例15: stock

# 需要导入模块: from urllib import request [as 别名]
# 或者: from urllib.request import quote [as 别名]
def stock(searchterm):
    searchterm = quote(searchterm)
    url = "https://www.shutterstock.com/search?searchterm={0}".format(
        searchterm)
    res = requests.get(url)
    soup = BeautifulSoup(res.text, "html5lib")
    images = ["https:" + x["src"] for x in soup.select(".img-wrap img")]
    shuffle(images)

    return images[0] if images else "" 
开发者ID:llimllib,项目名称:limbo,代码行数:12,代码来源:stockphoto.py


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