如何在Python中对一个查询字符串进行urlencode?

Jam*_*mes 521 python url-encoding

我在提交之前尝试对此字符串进行urlencode.

queryString = 'eventName=' + evt.fields["eventName"] + '&' + 'eventDescription=' + evt.fields["eventDescription"]; 
Run Code Online (Sandbox Code Playgroud)

Ric*_*cky 982

Python 2

你在寻找的是urllib.quote_plus:

>>> urllib.quote_plus('string_of_characters_like_these:$#@=?%^Q^$')
'string_of_characters_like_these%3A%24%23%40%3D%3F%25%5EQ%5E%24'
Run Code Online (Sandbox Code Playgroud)

Python 3

在Python 3中,urllib包已被分解为更小的组件.你会用urllib.parse.quote_plus(注意parse子模块)

import urllib.parse
urllib.parse.quote_plus(...)
Run Code Online (Sandbox Code Playgroud)

  • 这很好用,但在添加此参数safe ='; /?:@&= + $,'之后我无法访问某些在线服务(REST) (6认同)
  • 谢谢!在我的情况下,我需要把:`import urllib.parse ... urllib.parse.quote_plus(查询)` (4认同)
  • 非常好,但为什么不习惯Unicode?如果url字符串是Unicode,我必须将其编码为UTF-8.有没有其他方法可以做到这一点? (3认同)
  • @AmosJoshua我认为你在双圆括号`))`之后错过了一个双引号`"`,它应该是:`python3 -c "import urllib.parse, sys; print(urllib.parse.quote_plus(sys.argv[1]))" "要编码的字符串"` (2认同)

bgp*_*ter 527

您需要将参数传递urlencode()为映射(dict)或一系列2元组,如:

>>> import urllib
>>> f = { 'eventName' : 'myEvent', 'eventDescription' : 'cool event'}
>>> urllib.urlencode(f)
'eventName=myEvent&eventDescription=cool+event'
Run Code Online (Sandbox Code Playgroud)

Python 3或更高版本

使用:

>>> urllib.parse.urlencode(f)
eventName=myEvent&eventDescription=cool+event
Run Code Online (Sandbox Code Playgroud)

请注意,这并没有做URL编码的常用意义(查看输出).为此用途urllib.parse.quote_plus.

  • 从技术上讲,这是服务中的一个错误,不是吗? (15认同)
  • "请注意,urllib.urlencode并不总能解决问题.问题是某些服务关心参数的顺序,在创建字典时会丢失.对于这种情况,urllib.quote_plus更好,正如Ricky建议的那样. " (10认同)
  • 如果你只是想让字符串URL安全,而不构建一个完整的查询参数字符串,怎么会这样呢? (4认同)

X''*_*X'' 43

尝试请求而不是urllib,你不需要打扰urlencode!

import requests
requests.get('http://youraddress.com', params=evt.fields)
Run Code Online (Sandbox Code Playgroud)

编辑:

如果您需要有序的名称 - 值对名称的多个值,请设置params,如下所示:

params=[('name1','value11'), ('name1','value12'), ('name2','value21'), ...]
Run Code Online (Sandbox Code Playgroud)

而不是使用字典.

  • 这没有解决对名称值对进行排序的问题,这也需要安装外部库的权限,这可能对项目不可行. (4认同)

dre*_*mac 36

上下文

  • Python(2.7.2版)

问题

  • 您想要生成urlencoded查询字符串.
  • 您有一个包含名称 - 值对的字典或对象.
  • 您希望能够控制名称 - 值对的输出顺序.

  • urllib.urlencode
  • urllib.quote_plus

陷阱

以下是一个完整的解决方案,包括如何处理一些陷阱.

### ********************
## 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
  """ 
Run Code Online (Sandbox Code Playgroud)


Jan*_*sen 26

Python 3:

urllib.parse.quote_plus(string,safe ='',encoding = None,errors = None)

  • 我更喜欢`urllib.parse.quote()`我自己因为它使用`%20`而不是`+`. (16认同)
  • 或者urllib.parse.urlencode(f) (5认同)

use*_*279 21

请注意,urllib.urlencode并不总能解决问题.问题是某些服务关心参数的顺序,在创建字典时会丢失.对于这种情况,urllib.quote_plus更好,正如Ricky建议的那样.

  • 幸运的是urlencode也适用于OrderedDict :) (13认同)
  • 如果传递元组列表,它可以正常工作并保留顺序:`>>> import urllib >>> urllib.urlencode([('name', 'brandon'), ('uid', 1000)]) 'name=品牌&uid=1000'` (2认同)

Cha*_*lie 21

试试这个:

urllib.pathname2url(stringToURLEncode)
Run Code Online (Sandbox Code Playgroud)

urlencode不起作用,因为它只适用于字典.quote_plus没有产生正确的输出.

  • 在 Python 3 中,现在是 `urllib.request.pathname2url` (2认同)

小智 9

import urllib.parse\nquery = 'Hell\xc3\xb6 W\xc3\xb6rld@Python'\nurllib.parse.quote(query) # returns Hell%C3%B6%20W%C3%B6rld%40Python\n
Run Code Online (Sandbox Code Playgroud)\n


小智 7

在Python 3中,这对我有用

import urllib

urllib.parse.quote(query)
Run Code Online (Sandbox Code Playgroud)


bsc*_*ter 6

为了在需要同时支持 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'
Run Code Online (Sandbox Code Playgroud)


nic*_*nor 5

供将来参考(例如:适用于python3)

>>> import urllib.request as req
>>> query = 'eventName=theEvent&eventDescription=testDesc'
>>> req.pathname2url(query)
>>> 'eventName%3DtheEvent%26eventDescription%3DtestDesc'
Run Code Online (Sandbox Code Playgroud)


Nat*_*hat 5

如果 urllib.parse.urlencode() 出现错误,请尝试 urllib3 模块。

语法如下

import urllib3
urllib3.request.urlencode({"user" : "john" }) 
Run Code Online (Sandbox Code Playgroud)