selenium study notes

1. Browser operation
from selenium import webdriver
from import By
driver = webdriver.Chrome()
#Start the chromedriver service and connect to the chromedriver service
Open a browser. Open a session with the browser.
(2) Visit website
driver.get(“ ”)# first page
(3) Maximize window, minimize window
driver.maximize_window() # large
driver.minimize_window() # small
(4) Set window size
(5) Reload page - F5
(6) Go back to the previous page and move forward
(7) Go back to the next page and go back
(8) Close current window
driver.close() # just closes the current window. The session still exists.
(9) Close this session
driver.quit() # when everything is done, the session should be closed. Turn off the chromedriver service.
2. Element positioning 8 major positioning
#Type 1: find an element by its single attribute. 6 positioning methods:
#Class 2: combine attributes to locate elements There are two positioning methods for boys / settled in Beijing / Gao fushuai: xpath and css selector.
#1. id - id card. Dynamic id: # find element
#Location policy: id value: kw
#Find element: DOM tree.
#Gets the properties of the element.
#Optional elements: radio and checkbox
#Element is_enabled: Button - born clickable. If the status is disabled, the button is unavailable.
#Input box: - it is born to let users enter information. If it is read-only and cannot be edited (readonly attribute), it indicates that the input box is unavailable.
#8 ways to find child elements: find child elements in your descendant elements.
# send_keys: input operation
#Click: click operation
# is_displayed: whether the element is visible in the page.
#Three states of elements: element found < element visible < element available
(1)id location
element = driver.find_ element_ by_ The ID ("kw") # WebElement object encapsulates what you want to do with the element.
eels2 = driver.find_element("id","kw")
ele2 = driver.find_element(By.ID,"kw")
(2)tag_name tag name positioning.
el = driver.find_element_by_tag_name("input")
# driver.find_element(By.TAG_NAME,"input")
#Returns the first matching element.
els = driver.find_elements_by_tag_name("input")
# driver.find_elements(By.TAG_NAME,"input")
#Returns all matched elements== Lists are WebElement objects pri

(3)element name Attribute positioning
(4)class Attribute positioning
driver.find_element_by_class_name("bg")  # The parameter can only be a decoration style and a class value.

(5)(6)a element-Link.
# Returns the first matching element.
# Returns all matched elements== list
(7)xpath location:
	# Absolute positioning
	/html/body/div[2]/div/form/div[1]/input  # Locate level by level according to the path
	# Relative positioning the relative position of elements and filter by type
	# Basic usage:
	//Tag name [@ attribute name = value]
	# Logical operation:
	//Tag name [@ attribute name = value and/or @ attribute name = value]

	# Text positioning, unchanged attributes or files.
	//Tag name [contains(@ attribute / text(), content to be included)]

	# Hierarchical positioning, after defining the scope through ancestors, find yourself.
	# //div[@id="u1"]//a[@name="tj_login"]
(8)xpath Axis positioning

	# Axis operation:
	ancestor: Ancestor nodes include parent nodes
	parent:Parent node to g
	preceding: All nodes before the current element node label. ( html Page order)
	preceding-sibling: All sibling nodes before the current element node label
	following: All nodes after the current element node label. ( html Page order)
	following-sibling: All sibling nodes after the current element node label

	# Use syntax:
	Known elements/Axis name::Label name[@attribute=value]
	//DD [@ data Val = "Zhang Zhibo"] / following sibling:: DD [contains (@ class, "batscore")] / span
	driver.find_element_by_xpath(' //div[@id="u1"]//a[@name="tj_login"]')

3. Waiting time
(1) Forced waiting
time.sleep(3) # forced wait
(2) Implicit waiting
driver.implicitly_wait(30) # implicit wait, intelligent wait, element exists
(3) Explicit waiting
from import WebDriverWait
from import expected_conditions as EC
from import By

driver = webdriver.Chrome() # The start flag of the session.

# The login box pops up - the change of the page is 0.5 seconds by default
# WebDriverWait(driver, upper waiting limit, polling cycle). Until (condition)
loc = (By.ID,"TANGRAM__PSP_10__footerULoginBtn")
# EC.visibility_of_element_located(loc)
# Element visibility_of_element_located EC.visibility_of_element_located(loc)
# Elements are visible in EC.visibility_of_all_elements_located


4. Switch handle
from selenium import webdriver
driver = webdriver.Chrome() # session start flag.

# Search lemon class and click the first result of lemon class.
driver.find_element_by_id("kw").send_keys("Lemon class")
# To wait for the results to appear, select the first of the search results
loc = (By.XPATH,'//a[text() = "Tencent classroom - organization homepage"]))
# Causes a new window to appear.
# Wait for a new window to appear, and I'll switch windows.

(1)Get handles to all windows
wins = driver.window_handles
print("All window handles:",wins)

(2)Gets the handle of the current window
cur_win = driver.current_window_handle
print("The current window handle is:",cur_win)

(3)windows Switch to the latest open window
# New window
loc = (By.XPATH,'//UL [@ id = "JS tab"] / / H2 [contains (text(), "teacher")] ')
# EC.new_window_is_opened

(4)iframe switch
driver.switch_to.frame("login_frame_qq")  #name
driver.switch_to.frame(2)  # subscript
driver.switch_to.frame(driver.find_element_by_name('login_frame_qq'))  # webElement object
# After the switch is completed, it is directly located in the new html page.
# Cut it out and switch directly to the default main page
# Cut to previous iframe

(5)alert switch
from selenium import webdriver
driver = webdriver.Chrome()   # The start flag of the session.
# Do an action and a non html pop-up box appears
# switch
al = driver.switch_to.alert
# Turn off this pop-up box
al.dismiss()  # cancel
# al.accept()  # determine
print(al.text)  # Gets the text of the pop-up box

1,Explicit wait: WebdriverWait wait for\expected_condition condition
   Auxiliary waiting: sleep

2,3 Large switching 
   windows switch
   iframe switch
   alert switch
   1)Action: causes the window to open, iframe,alert appear.
   2)Find the window you want to switch:(Get all handles before switching to window handles),
					  iframe(name,Subscript webelement object)
   3) Switch: driver.switch_to.window/frame/alert
   4) close alert


(1)And unittest Differences between
	1)Use case writing? Support function
	2)Use case identification? Automatic identification. Identification rules? catalogue-file name-Use case name  pytest command line(pytest.main())
	3)Assertions of use cases? assert expression(The result is True,False) - logic/compare/Function return value. unittest:self.assertXXXX
	4)Use case report? unitest/pytest --html. however  pytest Yes, third-party reporting tools can be integrated-allure
	   pytest There are very rich plug-ins: 700+

(2)Commonalities of use case framework for writing use cases in language:
	1)Write use case: Pre, step, assertion, post. pytest How to express pre post?
	2)Run case: unitest,pytest    .main()
	3)Generate report:
	4)Organize use cases: the function of filtering use cases?
	5)Configuration when running case: case failed, retry(unittest Not included pytest Bring your own)
	6)Data driven support: unitest:ddt    pytest:Parameterization

(3)pytest Pre post:(Not with unittest,ddt coexistence)
	pytest: fixture - Front&Post.
    Level: 1. Regular meeting(session)Level: interface automation when the database connection.
         3,Test class(class)level
         4,test case(def/function)level

    Definition: a function contains pre and post.
         0) Determine the level: what is in the sandwich biscuit.
         1)How to distinguish between front and back? the galaxy:yield
         2)Function names can be defined arbitrarily. How can they be identified as pre and post?
            Function front@pytest.fixture
         3) What if the use case wants to use the variables in the front?
            Returns the variables to be used by the use case. yield Return value.
            When the use case is called, fixture The function name of is used as the parameter of the use case to receive its return value

    call(Use cases associated with test cases): 
    Use case level:
    Class,@pytest.mark.usefixtures("fixture Function name for")
    In front of the test function,@pytest.mark.usefixtures("fixture Function name for")

    # Conf -- pre post global share
    Scope: only use cases in the current directory and its descendants directory.
    Define each level of fixture
    fixture Can inherit fixture: ????

    # module \ session ???

	Parameterization: data driven   @pytest.mark.parametrize("case",LD.wrong_datas)

	Filter use cases: mark use cases.
	93 personal -- 93 Use cases
	Run: all sister paper! -- 40 Marks: Female
	1 Step: to pytest Register your token.  pytest.ini
	2 Step: mark the use cases that need to be marked.
		 Above the use case:@pytest.mark.Tagnames
	3 Step: run the marked use case. pytest Parameters:-m Tag name
(4)Data driven
(5)Use case tagging
	1)Register tag name: create a pytest.ini The first two lines of the configuration file are fixed format, and the third line is tag name
	2)Usage 1:Mark above the use case, and mark above the class (mark all test cases in the class),
	It can also be marked separately above the test case, and multiple test cases or classes can be marked repeatedly.
	@pytest.mark.Tag name
	3)Usage 2:You can also mark it under the use case class
	Mark the scope: test case, test class and module file. Under the test class, all use cases are marked with this label)
	class TestClass(object)
	pytestmark = pytest.mark.Tag name
	pytestmark= [pytest.mark.Label 1,pytest.mark.Label 2]#Multi label mode

	Similarly(py Under the file, all test functions and test functions in the test class have this label import pytest
	pytestmark = pytest.mark.webtest
	pytestmark= [pytest.mark.Label 1,pytest.mark.Label 2]#Multi label mode
	Run from the command line: pytest -m Tag name
	Run in script: pytest.main(["-m","Tag name"])
(6)Test report
(7)Repeat execution
	1)To install the rerun plug-in: pip install pytest-rerunfailures
	Run from the command line: pytest -m Tag name
	Run in script: pytest.main(["--reruns","2","--reruns-delay","5"]) #Rerun twice with an interval of 5 seconds


Tags: Front-end Selenium chrome

Posted on Sun, 05 Dec 2021 05:00:11 -0500 by TRB