Web automated testing - Selenium grammar introduction to proficiency

foreword

When it comes to automated testing, we have to mention the famous Selenium. Selenium is one of the most commonly used automated testing tools today. It supports rapid development of automated testing frameworks and supports testing on multiple browsers.

Selenium is less difficult to learn and has a short development cycle. For testers, if you have little programming experience, python + Selenium is a good choice. The grammar is simple and clear, which can significantly reduce the difficulty of later maintenance and work pressure.

Using Python+Selenium for automated testing can support multiple browsers, and crawlers can also be used to solve JavaScript rendering problems. Simulate a browser for web page loading

Today, we will introduce how to use Selenium to quickly start Web testing work!

1. Declare the browser object

Pay attention to point 1, the Python file name or package name should not be named selenium, which will lead to failure to import

from selenium import webdriver
#webdriver可以认为是浏览器的驱动器,要驱动浏览器必须用到webdriver,支持多种浏览器,这里以Chrome为例
browser = webdriver.Chrome()

2. Visit the page and get the html of the page

from selenium import webdriver
browser = webdriver.Chrome()
browser.get('https://www.taobao.com')
print(browser.page_source)#browser.page_source是获取网页的全部html
browser.close()

3. Find elements

single element

from selenium import webdriver
browser = webdriver.Chrome()
browser.get('https://www.taobao.com')
input_first = browser.find_element_by_id('q')
input_second = browser.find_element_by_css_selector('#q')
input_third = browser.find_element_by_xpath('//*[@id="q"]')
print(input_first,input_second,input_third)
browser.close()

Commonly used search methods

find_element_by_name
find_element_by_xpath
find_element_by_link_text
find_element_by_partial_link_text
find_element_by_tag_name
find_element_by_class_name
find_element_by_css_selector

You can also use the general method

from selenium import webdriver
from selenium.webdriver.common.by import By
browser = webdriver.Chrome()
browser.get('https://www.taobao.com')
input_first = browser.find_element(BY.ID,'q')#第一个参数传入名称,第二个传入具体的参数
print(input_first)
browser.close()
多个元素,elements多个s
input_first = browser.find_elements_by_id('q')

4. Element interaction operation - enter keywords in the search box for automatic search

More operations:

http://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.remote.webelement
#可以有属性、截图等等
browser = webdriver.Chrome()
url = 'http://www.runoob.com/try/try.php?filename=jqueryui-api-droppable'
browser.get(url)
browser.switch_to.frame('iframeResult')#切换到iframeResult框架
source = browser.find_element_by_css_selector('#draggable')#找到被拖拽对象
target = browser.find_element_by_css_selector('#droppable')#找到目标
actions = ActionChains(browser)#声明actions对象
actions.drag_and_drop(source, target)
actions.perform()#执行动作
更多操作:
http://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.common.action_chains

6. Execute JavaScript

Some actions may not provide api, such as the progress bar drop-down, at this time, we can execute JavaScript through code

from selenium import webdriver
browser = webdriver.Chrome()
browser.get('https://www.zhihu.com/explore')
browser.execute_script('window.scrollTo(0, document.body.scrollHeight)')
browser.execute_script('alert("To Bottom")')

7. Obtain element information

get attribute

from selenium import webdriver
from selenium.webdriver import ActionChains
browser = webdriver.Chrome()
url = 'https://www.zhihu.com/explore'
browser.get(url)
logo = browser.find_element_by_id('zh-top-link-logo')#获取网站logo
print(logo)
print(logo.get_attribute('class'))
browser.close()

get text value

from selenium import webdriver
browser = webdriver.Chrome()
url = 'https://www.zhihu.com/explore'
browser.get(url)
input = browser.find_element_by_class_name('zu-top-add-question')
print(input.text)#input.text文本值
browser.close()

#Get Id, location, tag name, size

from selenium import webdriver
browser = webdriver.Chrome()
url = 'https://www.zhihu.com/explore'
browser.get(url)
input = browser.find_element_by_class_name('zu-top-add-question')
print(input.id)#获取id
print(input.location)#获取位置
print(input.tag_name)#获取标签名
print(input.size)#获取大小
browser.close()

Eight, Frame operation

A frame is equivalent to an independent webpage. If you search for a subclass in the parent class network frame, you must switch to the subclass frame. If you search for the parent class, you also need to switch to the subclass first

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
browser = webdriver.Chrome()
url = 'http://www.runoob.com/try/try.php?filename=jqueryui-api-droppable'
browser.get(url)
browser.switch_to.frame('iframeResult')
source = browser.find_element_by_css_selector('#draggable')
print(source)
try:
logo = browser.find_element_by_class_name('logo')
except NoSuchElementException:
print('NO LOGO')
browser.switch_to.parent_frame()
logo = browser.find_element_by_class_name('logo')
print(logo)
print(logo.text)

Nine, wait

implicit wait

When the implicit wait is used to execute the test, if WebDriver does not find the element in the DOM, it will continue to wait, and throw an exception that the element cannot be found after the set time is exceeded.

In other words, when looking for an element or the element does not appear immediately, the implicit wait will wait for a period of time before looking up the DOM, the default time is 0

from selenium import webdriver
browser = webdriver.Chrome()
browser.implicitly_wait(10)
#等待十秒加载不出来就会抛出异常,10秒内加载出来正常返回
browser.get('https://www.zhihu.com/explore')
input = browser.find_element_by_class_name('zu-top-add-question')
print(input)

explicit wait

Specify a waiting condition and a maximum waiting time. The program will judge whether the condition is satisfied within the waiting time. If it is satisfied, it will return. If it is not satisfied, it will continue to wait. If the time exceeds, an exception will be thrown

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
browser = webdriver.Chrome()
browser.get('https://www.taobao.com/')
wait = WebDriverWait(browser, 10)
input = wait.until(EC.presence_of_element_located((By.ID, 'q')))
button = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '.btn-search')))
print(input, button)
title_is 标题是某内容
title_contains 标题包含某内容
presence_of_element_located 元素加载出,传入定位元组,如(By.ID, 'p')
visibility_of_element_located 元素可见,传入定位元组
visibility_of 可见,传入元素对象
presence_of_all_elements_located 所有元素加载出
text_to_be_present_in_element 某个元素文本包含某文字
text_to_be_present_in_element_value 某个元素值包含某文字
frame_to_be_available_and_switch_to_it frame加载并切换
invisibility_of_element_located 元素不可见
element_to_be_clickable 元素可点击
staleness_of 判断一个元素是否仍在DOM,可判断页面是否已经刷新
element_to_be_selected 元素可选择,传元素对象
element_located_to_be_selected 元素可选择,传入定位元组
element_selection_state_to_be 传入元素对象以及状态,相等返回True,否则返回False
element_located_selection_state_to_be 传入定位元组以及状态,相等返回True,否则返回False
alert_is_present 是否出现Alert
详细内容:
http://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.support.expected_conditions

11. Forward and backward - realize the forward and backward of the browser to browse different web pages

import time
from selenium import webdriver
browser = webdriver.Chrome()
browser.get('https://www.baidu.com/')
browser.get('https://www.taobao.com/')
browser.get('https://www.python.org/')
browser.back()
time.sleep(1)
browser.forward()
browser.close()

12. Cookies

from selenium import webdriver
browser = webdriver.Chrome()
browser.get('https://www.zhihu.com/explore')
print(browser.get_cookies())
browser.add_cookie({'name': 'name', 'domain': 'www.zhihu.com', 'value': 'germey'})
print(browser.get_cookies())
browser.delete_all_cookies()
print(browser.get_cookies())

Tab management increases browser windows

import time
from selenium import webdriver
browser = webdriver.Chrome()
browser.get('https://www.baidu.com')
browser.execute_script('window.open()')
print(browser.window_handles)
browser.switch_to_window(browser.window_handles[1])
browser.get('https://www.taobao.com')
time.sleep(1)
browser.switch_to_window(browser.window_handles[0])
browser.get('http://www.fishc.com')

Thirteen, exception handling

from selenium import webdriver
browser = webdriver.Chrome()
browser.get('https://www.baidu.com')
browser.find_element_by_id('hello')
from selenium import webdriver
from selenium.common.exceptions import TimeoutException, NoSuchElementException
browser = webdriver.Chrome()
try:
browser.get('https://www.baidu.com')
except TimeoutException:
print('Time Out')
try:
browser.find_element_by_id('hello')
except NoSuchElementException:
print('No Element')
finally:
browser.close()


              [The following is the most complete software test engineer learning knowledge architecture system diagram in 2023 that I compiled]


1. From entry to mastery of Python programming

2. Interface automation project actual combat

3. Actual Combat of Web Automation Project


4. Actual Combat of App Automation Project

5. Resume of first-tier manufacturers


6. Test and develop DevOps system

7. Commonly used automated testing tools


Eight, JMeter performance test

9. Summary (little surprise at the end)

life is long so add oil. Every effort will not be let down, as long as you persevere, there will be rewards in the end. Cherish your time and pursue your dreams. Don't forget the original intention, forge ahead. Your future is in your hands!

Life is short, time is precious, we cannot predict what will happen in the future, but we can grasp the present moment. Cherish every day and work hard to make yourself stronger and better. Firm belief, persistent pursuit, success will eventually belong to you!

Only by constantly challenging yourself can you constantly surpass yourself. Persist in pursuing your dreams and move forward bravely, and you will find that the process of struggle is so beautiful and worthwhile. Believe in yourself, you can do it!

                                 

Guess you like

Origin blog.csdn.net/nhb687096/article/details/132041187