Python 将字符串转换为有效的url内容
我需要分享这样的链接Python 将字符串转换为有效的url内容,python,url,parameters,Python,Url,Parameters,我需要分享这样的链接 mysite.com?url=https://anothersite.com&text=some text mysite.com?url=https%3A%2F%anothersite.com&text=some%20text 所以一定是这样 mysite.com?url=https://anothersite.com&text=some text mysite.com?url=https%3A%2F%anothersite.com&t
mysite.com?url=https://anothersite.com&text=some text
mysite.com?url=https%3A%2F%anothersite.com&text=some%20text
所以一定是这样
mysite.com?url=https://anothersite.com&text=some text
mysite.com?url=https%3A%2F%anothersite.com&text=some%20text
我可以用这种方法得到它
def URL():
try:
text = 'some text'
url = 'anothersite.com'
parameters = 'url=%s&text=%s' % (url , text)
for r,n in [(':','%3A') , (' ','%20') , ('/','%2F')]:
parameters = parameters.replace(r,n)
return 'mysite.com?%s' % parameters
except Exception as e:
print '%s (%s)' % (e.message, type(e))
return ""
它可以工作,但我必须指定每个字符,因此如果我的文本有一个“#”,我必须将,(“#,'%23')添加到我的列表中
有没有解决这个问题的好方法?使用和str.index
拆分字符串(如果需要拆分):
您可能对
safe
kwarg tourllib.parse.quote
感兴趣:
qs = 'mysite.com?url=https://anothersite.com&text=some text'
urllib.parse.quote(qs,safe='=?&')
Out[10]: 'mysite.com?url=https%3A%2F%2Fanothersite.com&text=some%20text'
从文档中:
RFC2396统一资源标识符(URI):通用语法列出
以下是保留字符
保留=“;”|“/”|“?”|“:“|“@”|“&”|“=”|“+”|
“$”|“,”
在上面的保留字符中,您似乎希望在查询字符串中保持=?&
不转义,请告诉它。它会逃过剩下的