개발/Python

Python에서 쿼리 문자열을 urlencode하는 방법은 무엇입니까?

MinorMan 2021. 1. 7. 08:36
반응형

<질문>

제출하기 전에이 문자열을 urlencode하려고합니다.

queryString = 'eventName=' + evt.fields["eventName"] + '&' + 'eventDescription=' + evt.fields["eventDescription"]; 

<답변1>

매개 변수를urlencode()다음과 같이 매핑 (dict) 또는 2- 튜플 시퀀스로 사용됩니다.

>>> 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.


<답변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'

Python 3에서는urllib패키지가 더 작은 구성 요소로 나뉩니다. 당신은 사용할 것입니다urllib.parse.quote_plus(참고parse자식 모듈)

import urllib.parse
urllib.parse.quote_plus(...)

<답변3>

시험requestsurllib 대신 urlencode로 귀찮게 할 필요가 없습니다!

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

편집하다:

필요한 경우정렬 된 이름-값 쌍또는 이름에 여러 값을 입력 한 다음 다음과 같이 매개 변수를 설정합니다.

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

사전을 사용하는 대신.


<답변4>

  • 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
  """ 

<답변5>

파이썬 3 :

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


<답변6>

이 시도:

urllib.pathname2url(stringToURLEncode)

urlencode사전에서만 작동하므로 작동하지 않습니다.quote_plus올바른 출력을 생성하지 않았습니다.


<답변7>

urllib.urlencode가 항상 트릭을 수행하는 것은 아닙니다. 문제는 일부 서비스가 사전을 만들 때 손실되는 인수의 순서에 관심이 있다는 것입니다. 이러한 경우 Ricky가 제안한 것처럼 urllib.quote_plus가 더 좋습니다.


<답변8>

Python 3에서 이것은 나와 함께 일했습니다.

import urllib

urllib.parse.quote(query)

<답변9>

향후 참조 용 (예 : python3 용)

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

<답변10>

Python 2와 3을 모두 지원해야하는 스크립트 / 프로그램에서 사용하기 위해 six 모듈은 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'

<답변11>

그만큼통사론다음과 같다 :

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

<답변12>

이미 언급되지 않았을 수있는 또 다른 것은urllib.urlencode()사전의 빈 값을 문자열로 인코딩합니다.None해당 매개 변수가없는 대신 이것이 일반적으로 바람직한 지 여부는 모르지만 내 사용 사례에 맞지 않으므로 사용해야합니다.quote_plus.


<답변13>

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')
반응형