Python: Google Suggest查询格式化

2024-04-26 03:31:03 发布

您现在位置:Python中文网/ 问答频道 /正文

代码不能同时处理多个关键字

例如,关键字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],'')]

谢谢你的帮助


Tags: 代码fromimportflasksearchgetrequest格式
1条回答
网友
1楼 · 发布于 2024-04-26 03:31:03

如果search_term中有任何空格,则在调用函数对URI(url.format())进行编码时,这些空格将转换为%20。在编码为URL安全格式之前,必须将它们替换为+:

request = urllib.request.Request(url.format(search_term.replace(' ','+')))

这将用+替换所有空格,然后将整个字符串编码为URI safe。你知道吗

相关问题 更多 >