本文整理匯總了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))
示例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)
示例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
示例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)
示例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=(.*?)&", result)))
shuffle(images)
if images:
return images[0]
return ""
示例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=(.*?)&", result)))
shuffle(gifs)
if gifs:
return gifs[0]
return ""
示例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
#用來正常顯示中文標簽
示例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
示例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)
示例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)
示例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])
示例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
示例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
示例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 ""
示例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 ""