Selenium2+python automation 43-judging title (title_is) Selenium2+python automation 42-judging elements (expected_conditions)

foreword

The method of obtaining the page title can be obtained directly with driver.title, and then the obtained result can also be used as an assertion.

This article introduces another method to determine whether the page title is the same as the expected result, using the previous Selenium2+python automation 42-judgment element (expected_conditions)

The title_is and title_contains methods mentioned in the expected_conditions module

 

1. Source code analysis

1. First look at the source code, as follows

class title_is(object):
    """An expectation for checking the title of a page.
    title is the expected title, which must be an exact match
    returns True if the title matches, false otherwise."""

    '''Translation: Check that the title of the page is exactly the same as the expected value, if it is exactly the same, return True, otherwise return Flase'''
    def __init__(self, title):
        self.title = title

    def __call__(self, driver):
        return self.title == driver.title

2. Comment translation: Check that the title of the page is exactly the same as the expected value. If it is exactly the same, return True, otherwise return Flase

3.title_is() This is a class type with two methods in it

4. __init__ is the initialization content, the parameter is title, required

5. __call__ is to turn the instance into an object, the parameter is driver, and the return is self.title == driver.title, a boolean value

 

2. Judging title:title_is()

1. First import the expected_conditions module

2. Since the name of this module is relatively long, it is renamed to EC for the convenience of subsequent calls (a bit like renaming when querying multiple tables in a database)

3. After opening the blog homepage, judge the title and return the result to True or False

 

3. Judging that the title contains: title_contains

1. This class is similar to the one above, but this is a partial match (similar to the contains syntax in xpath)

2. Judging that the title contains the string 'Shanghai-Yoyou'

 

4. Reference code

# coding:utf-8
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Firefox()
driver.get("http://www.cnblogs.com/yoyoketang")
# Judging that title is exactly equal to
title = EC.title_is(u'Shanghai-Yuyou-Blog Park')
print title(driver)

# Judging that the title contains
title1 = EC.title_contains(u'Shanghai-Yuyou')
print title1(driver)

# Another way of writing
r1 = EC.title_is(u'Shanghai-Yoyou-Blog Park')(driver)
r2 = EC.title_contains(u'Shanghai-Yoyou')(driver)
print r1
print r2

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325348309&siteId=291194637