使用Python查询solr请求';当查询规范中有空格时,返回urllb2

使用Python查询solr请求';当查询规范中有空格时,返回urllb2,python,solr,request,urllib,Python,Solr,Request,Urllib,我想以一种高效的方式在Python中查询Solr mlt术语。 我有一份全名清单,例如: names = ['Bobby Johnson', 'James Bob'] 要查询solr中每个人的mlt术语,您必须使用以下URL: 'http://localhost:8382/solr/core/mlt?q=name:"Bobby Johnson"&fl=*,score&mlt.fl=concepts&mlt.interestingTerms=detai

我想以一种高效的方式在Python中查询Solr mlt术语。 我有一份全名清单,例如:

names = ['Bobby Johnson', 'James Bob']
要查询solr中每个人的mlt术语,您必须使用以下URL:

'http://localhost:8382/solr/core/mlt?q=name:"Bobby Johnson"&fl=*,score&mlt.fl=concepts&mlt.interestingTerms=details'

'http://localhost:8382/solr/core/mlt?q=name:"James Bob"&fl=*,score&mlt.fl=concepts&mlt.interestingTerms=details'
正如您在上面的示例中所看到的,带空格的全名查询在引号中表示。这是有效的,除了重复性的工作,因为名单很大

如果我尝试更有效地执行此操作,通过使用f字符串查询for循环中列表中的每个项目,我会得到一个无效的URL错误(见下文)。 我的代码:

from urllib.request import urlopen

for name in names:
    req = urlopen(f'http://localhost:8382/solr/core/mlt?q=name:"{name}",score&mlt.fl=concepts&mlt.interestingTerms=details')
    request_json = json.load(req)
    interesting_terms = request_json['interestingTerms']
    print(interesting_terms)

#Error message:
InvalidURL: URL can't contain control characters. '/solr/core/mlt?q=name:"Bobby Johnson",score&mlt.fl=concepts&mlt.interestingTerms=details' (found at least ' ')

当查询包含空白时,有没有关于如何在Python中处理多个请求的具体想法/示例?


所需输出:能够发送列表中每个全名的请求,并以json格式返回信息。

在将URL发送到urlopen之前,您必须在生成URL时转义该值:

from urllib.request import urlopen
from urllib.parse import quote_plus

for name in names:
    req = urlopen(f'http://localhost:8382/solr/core/mlt?q=name:"{quote_plus(name)}",score&mlt.fl=concepts&mlt.interestingTerms=details')
    ...