代码不能同时处理多个关键字
例如,关键字1关键字2关键字3引用错误的URL格式:
/get_all_related/keyword1%20keyword2%20keyword3
而不是这个
/get_all_related/keyword1+keyword2+keyword3
如何获得所需的网址格式?你知道吗
代码如下:
from flask import Flask, render_template, jsonify
from urllib.parse import quote_plus
import json
import sys
import urllib.request
app = Flask(__name__)
url = 'http://suggestqueries.google.com/complete/search?client=firefox&q={}'
@app.route('/')
def index():
return render_template('index.html')
def get_related(entity):
search_term = quote_plus('{} vs '.format(entity))
request = urllib.request.Request(url.format(search_term))
result = urllib.request.urlopen(request)
suggestions = json.loads(result.read())
return [x.replace(suggestions[0],'') for x in suggestions[1] if 'vs' not in x.replace(suggestions[0],'')]
谢谢你的帮助
如果
search_term
中有任何空格,则在调用函数对URI(url.format()
)进行编码时,这些空格将转换为%20
。在编码为URL安全格式之前,必须将它们替换为+:request = urllib.request.Request(url.format(search_term.replace(' ','+')))
这将用+替换所有空格,然后将整个字符串编码为URI safe。你知道吗
相关问题 更多 >
编程相关推荐