51Testing软件测试论坛

标题: Python中Selenium的使用 [打印本页]

作者: 草帽路飞UU    时间: 2022-7-20 08:54
标题: Python中Selenium的使用

Selenium简介

安装Selenium-Python

Selenium-Server的安装与使用

Selenium常用操作

请求一个页面

查找元素

填写表格

拖放

在不同的窗口和框架之间移动

访问浏览器历史记录

操作Cookies

等待页面加载完成

显式等待

隐式等待







作者: 草帽路飞UU    时间: 2022-7-20 08:58

页面对象

python_test.py

page.py

element.py

locators.py


中文帮助:https://selenium-python-zh.readthedocs.io/en/latest/
           英文帮助:https://selenium-python.readthedocs.io/
           官方文档:https://seleniumhq.github.io/selenium/docs/api/py/api.html

Selenium简介

Selenium是一个Web的自动化测试工具,最初是为网站自动化测试而开发的。Selenium可以直接运行在浏览器上,它支持所有主流的浏览器(包括PhantomJS这类无界面的浏览器,PhantomJS是一个基于Webkit的“无界面”(headless)浏览器,它会把网站加载到内存并执行页面上的Javascript。),可以接收指令,让浏览器自动加载页面,获取需要的数据,甚至页面截屏。

Selenium还为Python提供了一些非常简洁方便的API,让你能够使用像Firefox、 IE、 Chrome、 Remote 等 Selenium WebDrivers 来编写功能/校验测试。 通过Selenium的API,你可以非常直观的使用Selenium WebDriver的所有功能。当前支持的 Python 版本为 2.7, 3.2及以上。

安装Selenium-Python

下载地址:https://pypi.python.org/pypi/selenium

或者:http://selenium-release.storage.googleapis.com/index.html

你可以使用 pip 命令来安装 Selenium:

pip install selenium

或者,使用 easy_install来安装 Selenium:

easy_install seleniumSelenium-Server的安装与使用

如果你想使用远程 WebDriver,你需要先安装一个Selenium-Server, Selenium-Server是一个JAVA工程,推荐在Java Runtime Environment (JRE) 1.6或者更高的版本上运行。

下载地址:https://www.seleniumhq.org/

你需要先安装好JDK或者JRE,然后,使用下面的命令运行Selenium-Server:

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

Selenium-Server 成功启动后, 你会看到这样的提示信息:

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

你可以通过提示中给出的 URL连接到远程WebDriver, 下面是一些例子:

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)




作者: 草帽路飞UU    时间: 2022-7-20 09:14

desired_capabilities 是一个字典,如果你不想使用默认的字典,你可以明确指定它的值:

Selenium常用操作请求一个页面

调用WebDriver 的 get 方法打开一个链接,WebDriver 将等待,直到页面完全加载完毕(onload 方法执行完毕), 然后才会继续执行get 方法后面的代码。 值得注意的是,如果你的页面使用了大量的Ajax加载, WebDriver可能不知道什么时候页面才会完成加载。 如果你想确保这些页面被完全加载,可以使用Waits操作。

查找元素

Selenium提供了下列方法用来定位一个元素:

下列方法用来一次查找多个元素 (返回一个list列表):

除了上述的公共方法,下面还有两个私有方法 find_element 和 find_elements :

下面是 By 类的一些可用属性:
ID = "id"
XPATH = "xpath"
LINK_TEXT = "link text"
PARTIAL_LINK_TEXT = "partial link text"
NAME = "name"
TAG_NAME = "tag name"
CLASS_NAME = "class name"
CSS_SELECTOR = "css selector"

填写表格

上面这段代码将会寻找页面第一个select元素, 并遍历他的每一个option元素, 打印它们的值,然后按顺序都选中一遍。
但这并不是处理 select 元素最好的方法。WebDriver的支持类包括一个叫做Select的类,他提供了一些更为便利的方法来处理这些内容:

或者,WebDriver对每一个元素都有一个叫做 submit 的方法,如果你在一个表单内的元素上使用该方法,WebDriver会在DOM树上就近找到最近的表单进行提交。 如果调用的元素不在表单内,将会抛出NoSuchElementException异常:

element.submit()拖放

你可以使用拖放,无论是移动一个元素,或放到另一个元素内:

在不同的窗口和框架之间移动

对于现在的web应用来说,没有任何frames或者只包含一个window窗口是比较罕见的。 WebDriver 支持在不同的窗口之间移动,只需要调用switch_to_window方法即可:

driver.switch_to.window("windowName")

所有的 driver 将会指向当前窗口,但是你怎么知道当前窗口的名字呢,查看打开他的javascript或者连接代码:

<a href="somewhere.html" target="windowName">Click here to open a new window</a>

你还可以在switch_to_window()中使用窗口句柄来打开它,你也可以使用窗口句柄迭代所有已经打开的窗口:


作者: 草帽路飞UU    时间: 2022-7-29 15:39
page.py

页面对象模式意图通过为每一个页面创建一个对象来实现测试代码和技术实现之间的分层解耦。

from element import BasePageElement

from locators import MainPageLocators

class SearchTextElement(BasePageElement):

    """This class gets the search text from the specified locator"""

    # The locator for search box where search string is entered

    locator = 'q'

class BasePage(object):

    """Base class to initialize the base page that will be called from all pages"""

    def __init__(self, driver):

        self.driver = driver

class MainPage(BasePage):

    """Home page action methods come here. I.e. Python.org"""

    # Declares a variable that will contain the retrieved text

    search_text_element = SearchTextElement()

    def is_title_matches(self):

        """Verifies that the hardcoded text "Python" appears in page title"""

        return "Python" in self.driver.title

    def click_go_button(self):

        """Triggers the search"""

        element = self.driver.find_element(*MainPageLocators.GO_BUTTON)

        element.click()

class SearchResultsPage(BasePage):

    """Search results page action methods come here"""

    def is_results_found(self):

        # Probably should search for this text in the specific page

        # element, but as for now it works fine

        return "No results found." not in self.driver.page_source


作者: 草帽路飞UU    时间: 2022-7-29 15:41
element.py from selenium.webdriver.support.ui import WebDriverWait


class BasePageElement(object):
    """Base page class that is initialized on every page object class."""

    def __set__(self, obj, value):
        """Sets the text to the value supplied"""
        driver = obj.driver
        WebDriverWait(driver, 100).until(
            lambda driver: driver.find_element_by_name(self.locator))
        driver.find_element_by_name(self.locator).send_keys(value)

    def __get__(self, obj, owner):
        """Gets the text of the specified object"""
        driver = obj.driver
        WebDriverWait(driver, 100).until(
            lambda driver: driver.find_element_by_name(self.locator))
        element = driver.find_element_by_name(self.locator)
        return element.get_attribute("value")

locators.py
from selenium.webdriver.common.by import By

class MainPageLocators(object):
    """A class for main page locators. All main page locators should come here"""
    GO_BUTTON = (By.ID, 'submit')

class SearchResultsPageLocators(object):
    """A class for search results locators. All search results locators should come here"""
    pass







欢迎光临 51Testing软件测试论坛 (http://bbs.51testing.com/) Powered by Discuz! X3.2