Hướng dẫn thư viện selenium python

Hướng dẫn thư viện selenium python

1. Python là gì

Python là một ngôn ngữ lập trình bậc cao, thông dịch, hướng đối tượng, đa mục đích và cũng là một ngôn ngữ lập trình động. Cú pháp của Python là khá dễ dàng để học và ngôn ngữ này cũng mạnh mẽ và linh hoạt không kém các ngôn ngữ khác trong việc phát triển các ứng dụng, nó được thiết kế một cách thân thiện, python sử dụng từ khóa bằng tiếng Anh căn bản để dễ dàng diễn tả.

2. Selenium là gì

Selenium là một trong những công cụ kiểm thử phần mềm tự động mã nguồn mở (open source test automation tool) mạnh nhất hiện nay cho việc kiểm thử ứng dụng Web. Selenium script có thể chạy được trên hầu hết các trình duyệt như IE, Mozilla FireFox, Chrome, Safari, Opera; và hầu hết các hệ điều hành như Windows, Mac, Linux.

Selenium WebDriver (Selenium 2): là thư viện cho phép người dung lập trình (scripting) test script trên các ngôn ngữ lập trình khác nhau như Python, Java, C#, Ruby…

3. Tại sao sử dụng selenium python

Selenium Python bindings cung cấp một API đơn giảm để viết functional/acceptance test sử dụng selenium webdriver.

Thông qua Selenium Python API bạn có thể truy cập tất cả các chức năng của selenium webdriver một cách trực quan.

Selenium Python bindings cung cấp một API thuận tiện để truy cập Webdrivers như Firefox, IE, Chrome, Remote. Hiện tại hỗ trợ Python version 2.7,3.2.

4. Downloading Python bindings cho selenium

Bạn có thể download Python bindings cho Selenium từ PyPI page cho gói selenium. Tuy nhiên một cách tiếp cận tốt hơn sẽ là sử dụng pip để install gói selenium. Python 3.5 có sẵn pip trong thư viện chuẩn. Sử dụng pip bạn có thể cài đặt selenium như sau:

pip install selenium

Bạn có thể nghiên cứu sử dụng virtualenv để tạo môi trường cô lập cho python. Python 3.5 có pyvenv nó hầu hết giống như virtualenv

5. Hướng dẫn chi tiết cho Window users

  1. Cài đặt Python 3.5 sử dụng MSI có sẵn trong python.org download page.

  2. Bắt đầu một command prompt sử dụng chương trình cmd.exe và run pip command như được đưa ra dưới đây để cài đặt selenium.

C:\Python35\Scripts\pip.exe install selenium

Bây giờ bạn có thể chạy test scripts của bạn sử dụng Python. Ví dụ nếu bạn tạo một Selenium script đơn giản và lưu nó trong C:\my_selenium_script.py, bạn có thể chạy nó như sau:

C:\Python35\python.exe C:\my_selenium_script.py

6. Downloading selenium server

Selenium server là một chương trình Java. Java Runtime Enviroment (JRE) 1.6 hoặc version mới hơn được đề nghị để chạy Selenium server

Bạn có thể download Selenium server 2.x từ download page của selenium website. File này nên có một số file như: selenium-server-standalone-2.x.x.jar. Bạn có thể download version mới nhất 2.x version của Selenium server.

Nếu Java Runtime Enviroment (JRE) không được cài đặt trong hệ thống của bạn, bạn có thể download JRE từ Oracle website. Nếu bạn đang sử dụng một hệ thống GNU/Linux và có quyền root truy cập trong hệ thống, bạn có thể cũng có thể sử dụng hướng dẫn hệ thống điều hành để cài đặt JRE.

Nếu java command là có sẵn trong PATH (enviroment variable), bạn có thể bắt đầu Selenium server sử dụng command:

java -jar selenium-server-standalone-2.x.x.jar

Replace 2.x.x with actual version of Selenium server you downloaded from the site.

Nếu JRE được cài đặt như là một non-root user hoặc nó không có sẵn trong PATH(enviroment variable), bạn có thể gõ đường dẫn tương đối hoặc tuyệt đối cho command. Tương tự như bạn cung cấp đường dẫn tương đối hoặc tuyệt đối tới Selenium server jar file sau đó command sẽ giống như này:

/path/to/java -jar /path/to/selenium-server-standalone-2.x.x.jar

7. Getting Started

7.1. Simple Usage

Nếu bạn đã cài đặt Selenium Python bindings, bạn có thể bắt đầu sử dụng nó như sau

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://www.python.org")
assert "Python" in driver.title
elem = driver.find_element_by_name("q")
elem.clear()
elem.send_keys("pycon")
elem.send_keys(Keys.RETURN)
assert "No results found." not in driver.page_source
driver.close()

Script trên có thể lưu trong file (eg:- python_org_search.py) sau đó có thể run như sau:

python python_org_search.py

Python bạn đang chạy nên có selenium module cài đặt.

7.2. Example Explained

Selenium.webdriver module cung cấp tất cả Webdriver implementations. Hiện nay hỗ trợ Webdriver implementations là Firefox, Chrome, IE và Remote. Lớp keys cung cấp keys trong keyboard như RETURN, F1, ALT, etc.

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

Firefox webDriver được tạo thì sử dụng câu lệnh:

driver = webdriver.Firefox()

Phương thức Driver.get sẽ điều hướng tới một page được cung cấp bởi URL.WebDriver sẽ đợi cho đến khi trang được tải xong. Trước khi trả lại điều khiển test hoặc script.

Điều đáng chú ý rằng nếu trang của bạn sử dụng nhiều AJAX để load thì WebDriver có thể biết khi nó load thành công.

driver.get("http://www.python.org")

Dòng lệnh tiếp theo là một assertion để xác nhận rằng trong tiêu đề có từ 'Python'

assert "Python" in driver.title

WebDriver cung cấp một số cách để tìm elements sử dụng một trong các cách tìm đó là: find_element_by_* methods.

Tiếp theo là input text element có thể được đặt bằng tên thuộc tính của nó sử dụng find_element_by_name method.

elem = driver.find_element_by_name("q")

Trường hợp gửi một keys, các phím đặc biệt có thể gửi sử dụng bởi lớp keys được import từ selenium.webdriver.common.keys.

elem.clear()
elem.send_keys("pycon")
elem.send_keys(Keys.RETURN)

Sau khi thực hiện một action nào đó trên page bạn nên lấy kết quả trả ra bằng cậu lệnh lấy message như dưới đấy:

assert "No results found." not in driver.page_source

Cuối cùng là phương thức close window như sau:

driver.close()

7.3. Using Selenium to write tests

Các gói selenium không cung cấp một công cụ testing/framework. Bạn có thể viết test cases sử dụng unit test module của Python. Một lựa chọn khác cho tool/frameworke là py.testnose

Trong chương này, chúng ta sử dụng unit test như framework là một lựa chọn. Dưới đây là một ví dụ sửa đổi trong đó sử dụng module unnit test. Đây là một thử nghiệm cho chức năng tìm kiếm của python.org

import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

class PythonOrgSearch(unittest.TestCase):

    def setUp(self):
        self.driver = webdriver.Firefox()

    def test_search_in_python_org(self):
        driver = self.driver
        driver.get("http://www.python.org")
        self.assertIn("Python", driver.title)
        elem = driver.find_element_by_name("q")
        elem.send_keys("pycon")
        elem.send_keys(Keys.RETURN)
        assert "No results found." not in driver.page_source

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

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

Và kết qủa sau khi chạy thành công thể hiện như ở dưới:

python test_python_org_search.py
.
----------------------------------------------------------------------
Ran 1 test in 15.566s

OK

7.4. Sử dụng Selenium với Remote WebDriver

Để sử dụng remote WebDriver, bạn nên có Selenium server đang chạy, để chạy server bạn sử dụng command như sau:

java -jar selenium-server-standalone-2.x.x.jar

Trong khi chạy Selenium server, bạn có thể nhìn thấy message như dưới đây:

15:43:07.541 INFO - RemoteWebDriver instances should connect to: http://127.0.0.1:4444/wd/hub

Bạn có thể sử dụng URL cho việc kết nối remote tới WebDrive, đây là một ví dụ

from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

driver = webdriver.Remote(
   command_executor='http://127.0.0.1:4444/wd/hub',
   desired_capabilities=DesiredCapabilities.CHROME)

driver = webdriver.Remote(
   command_executor='http://127.0.0.1:4444/wd/hub',
   desired_capabilities=DesiredCapabilities.OPERA)

driver = webdriver.Remote(
   command_executor='http://127.0.0.1:4444/wd/hub',
   desired_capabilities=DesiredCapabilities.HTMLUNITWITHJS)

Để xác định giá trị một cách rõ ràng thay thế dictionaries mặc định

driver = webdriver.Remote(
   command_executor='http://127.0.0.1:4444/wd/hub',
   desired_capabilities={'browserName': 'htmlunit',
                         'version': '2',
                        'javascriptEnabled': True})

Tài liệu tham khảo http://www.guru99.com/selenium-python.html http://selenium-python.readthedocs.io/getting-started.html