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

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

2. Text information

  • Element assignment
driver.find_element_by_xpath('//*[@id="kw"]').send_keys("Hu Ge")  # Search box input Hu Ge
  • Get text information
  • 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
    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
    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

3. Radio box, check box
. 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']"):

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

# Two positioning methods
  • Determine whether the control is selected
# Determine whether the control is selected
if driver.find_element_by_xpath("//*[@id='news']").is_selected():
    print('checked .')
    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

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

Operation result:

Topics: Mobile