[英]Invalid URI for url using ? in python requests module
I was trying to extract data using: 我试图使用以下方法提取数据:
urlall = url+'/'+i+'.json'+'\\?'+'page='+str(page)
r = requests.get(urlall)
I got an error 400 Client Error: Invalid URI for url: the '\?' turned out to be '%5C?'
if I use: 如果我使用:
urlall = url+'/'+i+'.json'+'?'+'page='+str(page)
Then I got another error: can only concatenate str (not "_io.TextIOWrapper") to str
How can I set '?' 如何设置“?” as a string and get only the '?'
作为字符串,并且仅获取“?” in the url instead of %5C?
在网址而不是%5C中?
You can use string formatting to create your resultant url ( string.format or f-strings ) 您可以使用字符串格式来创建结果网址( string.format或f-strings )
In [4]: url = 'http.example.com'
In [5]: i = 1
In [8]: page = 1
#f-strings for python>=3.6
In [10]: f'{url}/{i}.json?page={page}'
Out[10]: 'http.example.com/1.json?page=1'
#String formatting
In [11]: '{}/{}.json?page={}'.format(url, i, page)
Out[11]: 'http.example.com/1.json?page=1'
Or you can use urllib.parse.urlunsplit library to create your url, for example 或者您可以使用urllib.parse.urlunsplit库来创建您的url,例如
In [1]: from urllib.parse import urlunsplit
In [2]: urlunsplit(['http','example.com','1.json','page=1',''])
Out[2]: 'http://example.com/1.json?page=1'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.