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

问题描述 投票:0回答:15

我正在尝试在提交之前对该字符串进行 urlencode。

queryString = 'eventName=' + evt.fields["eventName"] + '&' + 'eventDescription=' + evt.fields["eventDescription"]; 
python urllib urlencode
15个回答
1265
投票

蟒蛇2

你要找的是

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'

蟒蛇3

在 Python 3 中,

urllib
包被分解成更小的组件。您将使用
urllib.parse.quote_plus
(注意
parse
子模块)

import urllib.parse
safe_string = urllib.parse.quote_plus(...)

705
投票

您需要将参数作为映射(字典)或二元组序列传递给

urlencode()
,例如:

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

Python 3 或以上版本

使用

urllib.parse.urlencode

>>> urllib.parse.urlencode(f)
eventName=myEvent&eventDescription=cool+event

请注意,这确实 not 在常用意义上进行 url 编码(查看输出)。对于那个用途

urllib.parse.quote_plus
.


90
投票

尝试 requests 而不是 urllib,你不需要为 urlencode 而烦恼!

import requests
requests.get('http://youraddress.com', params=evt.fields)

编辑:

如果您需要 有序的名称-值对 或一个名称的多个值,请像这样设置参数:

params=[('name1','value11'), ('name1','value12'), ('name2','value21'), ...]

而不是使用字典。


41
投票

上下文

  • 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"    : "[email protected]",
  }

### ********************
## 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
  """ 


27
投票

试试这个:

urllib.pathname2url(stringToURLEncode)

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


21
投票

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


13
投票

在 Python 3 中,这对我有用

import urllib

urllib.parse.quote(query)

6
投票

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

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

5
投票

如果 urllib.parse.urlencode() 给你错误,那么试试 urllib3 模块。

语法如下:

import urllib3
urllib3.request.urlencode({"user" : "john" }) 

5
投票

为了在需要同时支持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'

2
投票
import urllib.parse
query = 'Hellö Wörld@Python'
urllib.parse.quote(query) // returns Hell%C3%B6%20W%C3%B6rld%40Python


1
投票

另一件可能没有提到的事情是,

urllib.urlencode()
会将字典中的空值编码为字符串
None
,而不是让该参数不存在。我不知道这是否通常需要,但不适合我的用例,因此我必须使用
quote_plus
.


0
投票

对于 Python 3 urllib3 正常工作,您可以按照它的官方文档 如下使用:

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')

-2
投票

如果你不想使用urllib。

https://github.com/wayne931121/Python_URL_Decode

#保留字元的百分號編碼
URL_RFC_3986 = {
"!": "%21", "#": "%23", "$": "%24", "&": "%26", "'": "%27", "(": "%28", ")": "%29", "*": "%2A", "+": "%2B", 
",": "%2C", "/": "%2F", ":": "%3A", ";": "%3B", "=": "%3D", "?": "%3F", "@": "%40", "[": "%5B", "]": "%5D",
}

def url_encoder(b):
    # https://zh.wikipedia.org/wiki/%E7%99%BE%E5%88%86%E5%8F%B7%E7%BC%96%E7%A0%81
    if type(b)==bytes:
        b = b.decode(encoding="utf-8") #byte can't insert many utf8 charaters
    result = bytearray() #bytearray: rw, bytes: read-only
    for i in b:
        if i in URL_RFC_3986:
            for j in URL_RFC_3986[i]:
                result.append(ord(j))
            continue
        i = bytes(i, encoding="utf-8")
        if len(i)==1:
            result.append(ord(i))
        else:
            for c in i:
                c = hex(c)[2:].upper()
                result.append(ord("%"))
                result.append(ord(c[0:1]))
                result.append(ord(c[1:2]))
    result = result.decode(encoding="ascii")
    return result

#print(url_encoder("我好棒==%%0.0:)")) ==> '%E6%88%91%E5%A5%BD%E6%A3%92%3D%3D%%0.0%3A%29'
© www.soinside.com 2019 - 2024. All rights reserved.