【发布时间】:2011-08-02 05:28:38
【问题描述】:
我正在尝试在提交之前对这个字符串进行 urlencode。
queryString = 'eventName=' + evt.fields["eventName"] + '&' + 'eventDescription=' + evt.fields["eventDescription"];
【问题讨论】:
我正在尝试在提交之前对这个字符串进行 urlencode。
queryString = 'eventName=' + evt.fields["eventName"] + '&' + 'eventDescription=' + evt.fields["eventDescription"];
【问题讨论】:
您需要将参数作为映射 (dict) 或 2 元组序列传递给 urlencode(),例如:
>>> import urllib
>>> f = { 'eventName' : 'myEvent', 'eventDescription' : 'cool event'}
>>> urllib.urlencode(f)
'eventName=myEvent&eventDescription=cool+event'
Python 3 或更高版本
用途:
>>> urllib.parse.urlencode(f)
eventName=myEvent&eventDescription=cool+event
请注意,这不在常用意义上进行 url 编码(查看输出)。为此使用urllib.parse.quote_plus。
【讨论】:
你要找的是urllib.quote_plus:
safe_string = urllib.quote_plus('string_of_characters_like_these:$#@=?%^Q^$')
#Value: 'string_of_characters_like_these%3A%24%23%40%3D%3F%25%5EQ%5E%24'
在 Python 3 中,urllib 包已分解为更小的组件。您将使用urllib.parse.quote_plus(注意parse 子模块)
import urllib.parse
safe_string = urllib.parse.quote_plus(...)
【讨论】:
import urllib.parse ... urllib.parse.quote_plus(query)
python3 -c "import urllib.parse, sys; print(urllib.parse.quote_plus(sys.argv[1])) "string to encode" 用于命令行上的一行
)) 之后错过了双引号",它应该是:python3 -c "import urllib.parse, sys; print(urllib.parse.quote_plus(sys.argv[1]))" "string to encode"
【讨论】:
urllib.parse.quote(),因为它使用%20而不是+。
请注意,urllib.urlencode 并不总是有效。问题是一些服务关心参数的顺序,当你创建字典时它会丢失。对于这种情况,正如 Ricky 建议的那样, urllib.quote_plus 更好。
【讨论】:
>>> import urllib >>> urllib.urlencode([('name', 'brandon'), ('uid', 1000)]) 'name=brandon&uid=1000'
供将来参考(例如:python3)
>>> import urllib.request as req
>>> query = 'eventName=theEvent&eventDescription=testDesc'
>>> req.pathname2url(query)
>>> 'eventName%3DtheEvent%26eventDescription%3DtestDesc'
【讨论】:
'c:/2 < 3' 在 Windows 上的输出是 '///C://2%20%3C%203'。我想要一些只会输出'c:/2%20%3C%203'的东西。
尝试使用requests 代替 urllib,您无需为 urlencode 烦恼!
import requests
requests.get('http://youraddress.com', params=evt.fields)
编辑:
如果您需要有序的名称-值对或名称的多个值,请像这样设置参数:
params=[('name1','value11'), ('name1','value12'), ('name2','value21'), ...]
而不是使用字典。
【讨论】:
以下是一个完整的解决方案,包括如何处理一些陷阱。
### ********************
## init python (version 2.7.2 )
import urllib
### ********************
## first setup a dictionary of name-value pairs
dict_name_value_pairs = {
"bravo" : "True != False",
"alpha" : "http://www.example.com",
"charlie" : "hello world",
"delta" : "1234567 !@#$%^&*",
"echo" : "user@example.com",
}
### ********************
## setup an exact ordering for the name-value pairs
ary_ordered_names = []
ary_ordered_names.append('alpha')
ary_ordered_names.append('bravo')
ary_ordered_names.append('charlie')
ary_ordered_names.append('delta')
ary_ordered_names.append('echo')
### ********************
## show the output results
if('NO we DO NOT care about the ordering of name-value pairs'):
queryString = urllib.urlencode(dict_name_value_pairs)
print queryString
"""
echo=user%40example.com&bravo=True+%21%3D+False&delta=1234567+%21%40%23%24%25%5E%26%2A&charlie=hello+world&alpha=http%3A%2F%2Fwww.example.com
"""
if('YES we DO care about the ordering of name-value pairs'):
queryString = "&".join( [ item+'='+urllib.quote_plus(dict_name_value_pairs[item]) for item in ary_ordered_names ] )
print queryString
"""
alpha=http%3A%2F%2Fwww.example.com&bravo=True+%21%3D+False&charlie=hello+world&delta=1234567+%21%40%23%24%25%5E%26%2A&echo=user%40example.com
"""
【讨论】:
试试这个:
urllib.pathname2url(stringToURLEncode)
urlencode 不起作用,因为它仅适用于字典。 quote_plus 没有产生正确的输出。
【讨论】:
my string 转换为 my%20string。你的解决方案就像一个魅力!
%20 而不是+。谢谢
urllib.request.pathname2url
在 Python 3 中,这对我有用
import urllib
urllib.parse.quote(query)
【讨论】:
语法如下:
import urllib3
urllib3.request.urlencode({"user" : "john" })
【讨论】:
另一件可能没有提到的事情是urllib.urlencode() 将字典中的空值编码为字符串None,而不是让该参数不存在。我不知道这是否通常需要,但不适合我的用例,因此我必须使用quote_plus。
【讨论】:
对于需要同时支持python 2和3的脚本/程序,六模块提供了quote和urlencode函数:
>>> from six.moves.urllib.parse import urlencode, quote
>>> data = {'some': 'query', 'for': 'encoding'}
>>> urlencode(data)
'some=query&for=encoding'
>>> url = '/some/url/with spaces and %;!<>&'
>>> quote(url)
'/some/url/with%20spaces%20and%20%25%3B%21%3C%3E%26'
【讨论】:
对于 Python 3 urllib3 正常工作,您可以按照其official docs 如下使用:
import urllib3
http = urllib3.PoolManager()
response = http.request(
'GET',
'https://api.prylabs.net/eth/v1alpha1/beacon/attestations',
fields={ # here fields are the query params
'epoch': 1234,
'pageSize': pageSize
}
)
response = attestations.data.decode('UTF-8')
【讨论】:
import urllib.parse
query = 'Hellö Wörld@Python'
urllib.parse.quote(query) // returns Hell%C3%B6%20W%C3%B6rld%40Python
【讨论】:
urllib.parse.quote 已在 this earlier answer 中提及。