How to handle unicode in Python?

 How to handle unicode in Python?

In this article, we will demo the key tips to handle the unicode issue in python.

Take this website as an example, http://shopping.pchome.com.tw/

If we click the search button without any input character, it will show warning alert with Chinese Characters.

How do we capture and verify if the alert message in Chinese is what we expect?

First, we need to define the encoding utf-8 in the very beginning.
#-*- coding: utf-8 -*-

 

Then, we save the alert message by using switch_to_alert()

# switch to the alert
alert = self.driver.switch_to_alert()

# get the text from alert
alert_text = alert.text

 

Finally, we compare if the alert text equals what we expected. What need to mention here is that we convert both desired and expected text into unicode.

This can be optional in python 3.0, but it’s a required in python 2.7.

self.assertEqual(u"請輸入查詢關鍵字", unicode(alert_text))

 

[pastacode lang=”python” message=”How to Handle Unicode ” highlight=”1,32,33″ provider=”manual”]

#-*- coding: utf-8 -*-  

from selenium import webdriver
import unittest
class CompareProducts(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Firefox()
        self.driver.implicitly_wait(30)
        self.driver.maximize_window()
        self.driver.get("http://shopping.pchome.com.tw/index/")

    def test_compare_products_removal_alert(self):
        # get the search textbox
        search_field = self.driver.find_element_by_id("keyword")
        search_field.clear()
        search_field.send_keys("")


        # click the button
        SearchButton = self.driver.find_element_by_id("doSearch")
        SearchButton.click()


        # an alert to the user
        # switch to the alert
        alert = self.driver.switch_to_alert()

        # get the text from alert
        alert_text = alert.text
        # check alert text
        print "alert.text = " + alert_text
        # 程式開頭記得加入,否則會無法用中文註解  #-*- coding: utf-8 -*-  
        # 在Python3因為字串已經全部統一成 unicode ,所以不必加上 u ,這是Python2和Python3的重要差別之一,需要特別注意
        self.assertEqual(u"請輸入查詢關鍵字", unicode(alert_text))
        # click on Ok button
        alert.accept()

    def tearDown(self):
        self.driver.quit()

if __name__ == "__main__":
    unittest.main()

[/pastacode]

 

Leave a Reply

Your email address will not be published. Required fields are marked *