Строка в url python

How to encode URLs in Python

How to encode URLs in Python

URL encoding is often needed when you’re calling a remote api with additional query strings or path parameters. Any query string or path parameter placed in the URL must be properly URL encoded.

URL encoding is also required while preparing data for submission with application/x-www-form-urlencoded MIME type.

In this article, you’ll learn how to encode URL components in Python. Let’s get started!

URL Encoding query strings or form parameters in Python (3+)

In Python 3+, You can URL encode any string using the quote() function provided by urllib.parse package. The quote() function by default uses UTF-8 encoding scheme.

>>> import urllib.parse >>> query = 'Hellö Wörld@Python' >>> urllib.parse.quote(query) 'Hell%C3%B6%20W%C3%B6rld%40Python'

Note that, the quote() function considers / character safe by default. That means, It doesn’t encode / character

The quote() function accepts a named parameter called safe whose default value is / . If you want to encode / character as well, then you can do so by supplying an empty string in the safe parameter like this-

Читайте также:  Только латинские буквы java

Encoding space characters to plus sign ( + ) using quote_plus() function

The quote() function encodes space characters to %20 . If you want to encode space characters to plus sign ( + ), then you can use another function named quote_plus provided by urllib.parse package.

>>> import urllib.parse >>> query = 'Hellö Wörld@Python' >>> urllib.parse.quote_plus(query) 'Hell%C3%B6+W%C3%B6rld%40Python'

Encoding multiple parameters at once

You can encode multiple parameters at once using urllib.parse.urlencode() function. This is a convenience function which takes a dictionary of key value pairs or a sequence of two-element tuples and uses the quote_plus() function to encode every value. The resulting string is a series of key=value pairs separated by & character.

>>> import urllib.parse >>> params = 'q': 'Python URL encoding', 'as_sitesearch': 'www.urlencoder.io'> >>> urllib.parse.urlencode(params) 'q=Python+URL+encoding&as_sitesearch=www.urlencoder.io'

If you want the urlencode() function to use the quote() function for encoding parameters, then you can do so like this —

urllib.parse.urlencode(params, quote_via=urllib.parse.quote)

Encoding multiple parameters at once where one parameter can have multiple values

The urlencode() function takes an optional argument called doseq . If your input can have multiple values for a single key, then you should set the doseq argument to True so that all the values are encoded properly —

>>> import urllib.parse >>> params = 'name': 'Rajeev Singh', 'phone': ['+919999999999', '+628888888888']> >>> urllib.parse.urlencode(params, doseq=True) 'name=Rajeev+Singh&phone=%2B919999999999&phone=%2B628888888888'

URL Encoding in Python 2.x

In Python 2.x the quote() , quote_plus() , and urlencode() functions can be accessed directly from the urllib package. These functions were refactored into urllib.parse package in Python 3.

The following examples demonstrate how you can perform URL encoding in Python 2.x using the above functions.

>>> import urllib >>> urllib.quote('Hello World@Python2') 'Hello%20World%40Python2'
>>> import urllib >>> urllib.quote_plus('Hello World@Python2') 'Hello+World%40Python2'
>>> import urllib >>> params = 'q': 'Python 2.x URL encoding', 'as_sitesearch': 'www.urlencoder.io'> >>> urllib.urlencode(params) 'q=Python+2.x+URL+encoding&as_sitesearch=www.urlencoder.io'

Источник

How to urlencode in Python?

Whenever contacting a web API containing extra query strings or route arguments, URL encoding is frequently required. Any query phrase or route argument inside the URL should be URL encrypted correctly. When formulating information for submission using the application/x-www-form-urlencoded MIME format, URL encoding is necessary. You’ll discover how to encrypt URL fragments in Python throughout this article.

Example 01: Use of Quote Function On String

First of all, log in from the Ubuntu 20.04 system and try opening the shell terminal on it. You can open the shell by Ctrl+Alt+T shortcut key. After opening it, you have to create a new python file with any name using the touch instruction below. You can see we have named the file “test.py.”

To understand the concept of the encoding URL, we need to understand the concept of encoding a string first. Hence in this example, we will see how to encode a string. Your newly created file is located in the home directory of your system. Hence, open the file explorer and navigate towards the home directory. Open the newly created file by double-clicking on it. Write the code shown below in your file and save it. You can see this code contains the python-support at its first line. After that, you need to import a “urllib” library required to encode any URL. You can see we have imported the class “parse” from this library as well. This is to use the functions that it occupies for the parsing of any string. After that, we have defined a string named “str” with some string value in it. Then we have used the “quote” function utilizing parse class and “urllib” to encode the variable “str” value and save it into a new variable, “new.” On the fifth line, we have printed the encoded string “new.”

#!/usr/bin/python
import urllib . parse
str = «HY! MY name is Aqsa Yasin.»
new = urllib . parse . quote ( str )
print ( new )

Execution of this file takes place at the terminal via the python3 query as below. The output result is showing the encoding of a string successfully.

Example 02: Use of Urlencode Function On String

In the above example, you have seen that we have used the quote() function to encode or quote a string-type variable, and it worked perfectly. On the other hand, you need to understand that we cannot apply the “urlencode” method on any string because the string cannot be encoded into any URL. Let’s have a look at this for once. Open the same file again and update the code as below. You have just to change the function from “quote” to “urlencode” in this code. All the remaining statements are the same. Save your file and close it.

#!/usr/bin/python
import urllib . parse
str = «HY! MY name is Aqsa Yasin.»
new = urllib . parse . urlencode ( str )
print ( new )

To run the file, use the stated-below query in your command-shell of the Ubuntu system. After running the python file, we have encountered an exception of “TypeError.” This means the function “urlencode” cannot be applied to the string type variable at any cost.

Example 03: Use of Urlencode Function On Dictionary

From the above two examples, we have understood that to apply the urlencode function; we must have some other type variable for this. Hence open the same file test.py from the home folder of the Linux system. After opening it, update it with the script shown in the small snapshot image beneath. We have added the same library, “urllib,” and imported its parse class along with it. Then we have declared a list dictionary with 2 keys and 2 values. Then we have used this dictionary in the parenthesis of the function “urlencode” of a class parse and package urllib to encode it into a URL format. This encoded URL will then saved into a variable “new” and printed out on the terminal by a print statement at line 5. You can save the python file by click on the Save button at the top of a file or simply using “Ctrl+S.” After saving it, click on the “Cross” sign on the right side of the file window to close it.

#!/usr/bin/python
import urllib . parse
l = { «Name» : «Aqsa» , «SurName» : «Yasin» }
new = urllib . parse . urlencode ( 1 )
print ( new )

Let’s execute our python file once again by a stated-below instruction. The resultant output is showing the encoded format of a dictionary. It is showing clearly that the “Name” of a person is “Aqsa,” separating by the “=” sign. Also, it is separating One key value from another, e.g., Name and Surname.

Example 04: Use of Urlencode On Multiple-Valued Dictionary

Open the test.py file and update the code with the below script. This time we have been using the multiple-type value dictionary list in our code. You can see clearly that the dictionary contains a list as a value in it. Now we will see how the “urlencode” method works on it. We have used the dictionary “l” in the parameter of a “urlencode” method with “doseq” value as “True” to avoid special characters in our output. After that, we have printed the encoded value. Save your file using “Ctrl+S” and hit the cross button on the right corner of the file window to quit it.

#!/usr/bin/python
import urllib . parse
l = { ‘Name’ : ‘Aqsa’ , ‘Salary’ : [ 50000 , 80000 ] }
new = urllib . parse . urlencode ( l , doseq = True )
print ( new )

Let’s execute the file to see the working of the urlencode method by a query stated-beneath. The output shows that the encoded value shows the two separate values for the key “Salary.” This means urlencode works correctly on multitype dictionary lists.

Example 05: Use of Urlencode On Dictionary

This time we will be using a URL as a value to a dictionary key. So, open the file “test.py” and update its code with the below-shown one. You can see we have used the URL as a value to key.

#!/usr/bin/python
import urllib . parse
str = { ‘The encoded’ : ‘url is’ , ‘this =’ : ‘www.aiou.gov.pk’ }
new = urllib . parse . urlencode ( str )
print ( new )

Execution of this code shows us the encoded version of dictionary contents.

Conclusion:

We have done almost all possible examples of the “urlencode” method in our guide. Hope you will find no error while implementing these examples.

About the author

Aqsa Yasin

I am a self-motivated information technology professional with a passion for writing. I am a technical writer and love to write for all Linux flavors and Windows.

Источник

How To Encode URL and Query String In Python?

How To Encode URL and Query String In Python?

URL or Uniform Resource Locator is a technology and standard used to define different digital resources. The URL is well known with the website addresses like https://www.pythontect.com. Python provides different methods in order to encode the URL properly in order to form it in a global form. The urllib.parse module can be used to encode URL and Query String. This module can parse the following protocols.

file , ftp , gopher , hdl , http , https , imap , mailto , mms , news , nntp , prospero , rsync , rtsp , rtspu , sftp , shttp , sip , sips , snews , svn , svn+ssh , telnet , wais , ws , wss

Python URL Encode Methods

Python provides the following methods in order to encode a URL or query string.

Encode URL with quote() Method

Python provides the quote() method which will encode the provided string. The quote() method is provided by the urllib.parse module which is a built-in module. There is no need to install this module just importing it will work.

import urllib.parse URL = "https://www.pythontect.com/about/?name=ismail&pass=123" encoded_URL = urllib.parse.quote(URL) print(encoded_URL)

The encoded URL which will be printed to the standard output will be like below.

https%3A//www.pythontect.com/about/%3Fname%3Dismail%26pass%3D123

As we can see from the encoded URL some signs like / do not encode into different characters. But there is a way that encodes the URL safer by encoding all non-alphabet characters. The safe parameter can be set empty string which will convert all non-alphabet characters.

import urllib.parse URL = "https://www.pythontect.com/about/?name=ismail&pass=123" encoded_URL = urllib.parse.quote(URL,safe="") print(encoded_URL)

The output will be like below.

https%3A%2F%2Fwww.pythontect.com%2Fabout%2F%3Fname%3Dismail%26pass%3D123

Encode URL or Query String with urlencode() Method

Another method to encode a URL is the urlencode() method which is provided via urllib.parse module too. As a built-in module just importing the urllib.parse module will work without problem. URL encoding is especially used for encoding query strings where they consist of key-value pairs which are very same as the dictionary items. The parameters are provided as a dictionary to the urlencode() method.

import urllib.parse query_string = < "username":"ismail baydan" , "password":"123">encoded_URL = urllib.parse.urlencode( query_string ) print(encoded_URL)

The output will be like below.

username=ismail+baydan&password=123

Encode Space As + Sign

By default the urllib.parse() method encodes the spaces as %20 . This is the most popular method to encode space. But alternatively, space can be encoded as + sign by using the urllib.parse.quote_plus() method like below.

import urllib.parse URL = "https://www.pythontect.com/about/?name=ismail baydan&pass=123" encoded_URL = urllib.parse.quote_plus(URL,safe="") print(encoded_URL)

The output is like below where the space between “ismail” and “baydan” is enoded as “+”.

https%3A%2F%2Fwww.pythontect.com%2Fabout%2F%3Fname%3Dismail+baydan%26pass%3D123

Источник

Оцените статью