Python http url encode

How to url encode in python 3?

URL encoding is a method of converting special characters in a URL into a format that can be transmitted over the internet. In Python, the process of URL encoding can be done using the urllib.parse module, which contains several functions for working with URLs. In this article, we will discuss the various methods available for URL encoding in Python 3.

Method 1: urllib.parse.quote()

To URL encode a string in Python 3, you can use the urllib.parse.quote() function. This function takes a string as input and returns a URL-encoded string.

Here’s an example of how to use urllib.parse.quote() :

import urllib.parse url = 'https://www.example.com/search?q=python tutorial' encoded_url = urllib.parse.quote(url) print(encoded_url)
https%3A//www.example.com/search%3Fq%3Dpython%20tutorial

In this example, we first import the urllib.parse module which contains the quote() function. We then define a URL string with a query parameter. We pass this URL string to the quote() function to get the URL-encoded string. Finally, we print the encoded URL string.

The quote() function can also take an optional safe parameter which specifies additional characters that should not be encoded. For example, if you want to encode a URL string but leave the forward slashes ( / ) unencoded, you can pass the safe=’/’ parameter:

import urllib.parse url = 'https://www.example.com/search?q=python tutorial' encoded_url = urllib.parse.quote(url, safe='/') print(encoded_url)
https://www.example.com/search?q=python%20tutorial

In this example, we pass the safe=’/’ parameter to the quote() function. This tells the function to leave the forward slashes unencoded.

That’s it! With urllib.parse.quote() , you can easily URL encode strings in Python 3.

Method 2: urllib.parse.quote_plus()

To URL encode in Python 3 using urllib.parse.quote_plus() , follow these steps:

encoded_string = urllib.parse.quote_plus("Hello, world!")

The quote_plus() function replaces special characters in the string with their URL-encoded equivalents. For example, the space character is replaced with %20 .

import urllib.parse original_string = "Hello, world!" encoded_string = urllib.parse.quote_plus(original_string) print("Original string:", original_string) print("Encoded string:", encoded_string)
Original string: Hello, world! Encoded string: Hello%2C+world%21

In the example above, the original string is «Hello, world!» , and the encoded string is «Hello%2C+world%21» . The %2C represents the URL-encoded comma character, and %21 represents the URL-encoded exclamation mark character.

You can also pass additional arguments to the quote_plus() function to customize its behavior. For example, you can specify a different character encoding:

import urllib.parse original_string = "Hello, world!" encoded_string = urllib.parse.quote_plus(original_string, encoding="utf-8") print("Original string:", original_string) print("Encoded string:", encoded_string)
Original string: Hello, world! Encoded string: Hello%2C+world%21

In this example, we specified the encoding argument as «utf-8» , which is the default encoding used by quote_plus() .

Читайте также:  Как устанавливать плагины css

Method 3: urllib.parse.urlencode()

To URL encode in Python 3 with urllib.parse.urlencode() , you can follow these steps:

from urllib.parse import urlencode
params = 'param1': 'value1', 'param2': 'value2'>
encoded_params = urlencode(params)

Here’s another example with more parameters:

params = 'name': 'John Doe', 'age': 30, 'city': 'New York'> encoded_params = urlencode(params) print(encoded_params)
name=John+Doe&age=30&city=New+York

Note that the urlencode function automatically encodes special characters such as spaces ( ) to + and non-ASCII characters to their corresponding percent-encoded values.

You can also pass the doseq parameter as True to encode multiple values for the same key as separate parameters:

params = 'param1': ['value1', 'value2'], 'param2': 'value3'> encoded_params = urlencode(params, doseq=True) print(encoded_params)
param1=value1¶m1=value2¶m2=value3

That’s it! With urllib.parse.urlencode() , you can easily encode parameters for URLs in Python 3.

Method 4: using the percent-encoding in string format

To URL encode in Python 3 using the percent-encoding in string format, you can use the urllib.parse module. Here are the steps:

string_to_encode = "Hello, world!"
encoded_string = urllib.parse.quote(string_to_encode)
import urllib.parse string_to_encode = "This is a test string with spaces and special characters: !@#$%^&*()_+-=[]<>|;':\",./<>?" encoded_string = urllib.parse.quote(string_to_encode) print(encoded_string)
This%20is%20a%20test%20string%20with%20spaces%20and%20special%20characters%3A%20%21%40%23%24%25%5E%26%2A%28%29_%2B-%3D%5B%5D%7B%7D%7C%3B%27%3A%22%2C.%2F%3C%3E%3F

That’s it! You can use this method to URL encode any string in Python 3.

Источник

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.

Источник

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