Automatic testing of python + selenium -- basic operation of elements

Posted by PantherX on Sat, 02 May 2020 17:12:08 +0200

1. Positioning through CSS
find_element_by_css_selector()

driver.find_element_by_css_selector("#kw").send_keys("Hu Ge")  # Baidu home page input box

2. Text information

  • Element assignment
    .send_keys()
driver.find_element_by_xpath('//*[@id="kw"]').send_keys("Hu Ge")  # Search box input Hu Ge
  • Get text information
    .text
driver.find_element_by_id('TANGRAM__PSP_10__error').text
  • Assertion text information
# 1) Write the field to the XPath expression directly. If you can locate the element through the XPath, it means that the error field has been displayed on the page
try:
    driver.find_element_by_xpath('//*[@ id = "Tangram · PSP · 10 · error" and text() = "please input your mobile phone / email / user name"] ').is_displayed()
    print("Test successful with error message")
except Exception as e:
    print("Test failed.", format(e))

# 2) This method is recommended
#   element.text gets the value, and takes the text value and the expected result to match the string
error_mes = driver.find_element_by_id('TANGRAM__PSP_10__error').text
try:
    assert error_mes == "Please input your mobile phone/mailbox/user name"
    print("Pass the test")
except Exception as e:
    print("Test failed.", format(e))
  • Clear text messages
    .clear()
driver.find_element_by_id("kw").clear()

3. Radio box, check box
*Click
. click() check a button to call the click method of the element
Radio box click: take Baidu news page as an example

Use the for statement to traverse the two radio buttons and click them one by one

# Find elements by XPath ()
for i in driver.find_elements_by_xpath("//*/input[@type='radio']"):
    i.click()

Check box is the same, such as "next automatic login button" on Baidu login pop-up window:

# Two positioning methods
driver.find_element_by_xpath('//*[@id="TANGRAM__PSP_10__memberPass"]').click()
time.sleep(1)
driver.find_element_by_id("TANGRAM__PSP_10__memberPass").click()
  • Determine whether the control is selected
    .is_selected()
# Determine whether the control is selected
if driver.find_element_by_xpath("//*[@id='news']").is_selected():
    print('checked .')
else:
    print('Not selected.')

4. Get page source code, get matching field
Get source code. page_source

'''
Get a short book - contact all of our mailboxes
'''
#Get page source code
doc = driver.page_source
 #findall returns a list of matching substrings
 #Using regularization, find the field matching mailbox
emails = re.findall(r'[\w]+@[\w\.-]+',doc)

5. Page element size
.size

# Page element size
search_btn = driver.find_element_by_id('su')  # Search button
print(search_btn.size)

Operation result:

Topics: Mobile