Technical dry goods - Selenium Python usage skills (2)

Table of contents

Conduct automated cross-browser testing

Using CSS Locators

HTML source code of WebElement

mouseover

close the tab instead of the browser

Handle the dropdown menu

checkbox handling

Select elements with CSS selectors

Summarize:


Conduct automated cross-browser testing

You may need to test your code against different browsers (e.g. Firefox, Chrome, Internet Explorer, Edge) under multiple conditions. The practice of testing a website across different browsers is called automated browser testing. To perform automated browser testing using Selenium automated tests, you should pytestincorporate selective handling of these browsers in your unit test code or code. A code snippet (exploitation) is shown below pytestto handle multiple browsers:

''' 导入必要的包和类 '''

import pytest
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
from time import sleep

@pytest.fixture(params=["chrome", "firefox"],scope="class")
def driver_init(request):
    if request.param == "chrome":
        # 搞点事情
    if request.param == "firefox":
        # 搞定事情
    yield
    web_driver.close()
    ...........
    ...........

Using CSS Locators

When performing test automation with Selenium, positioning web elements on the page is the basis of the automation script. If you want to perform conditional execution based on the presence of a specific kind of web element (like Tag, Class, ID, etc.), you can use the find_elements_*** API. Some of them are mentioned below

  • find_elements_by_class_name(): Find elements by class name

  • find_elements(): find elements by strategy and locator

  • find_element_by_link_text(): Find elements by link text

  • find_element_by_partial_link_text(): Find elements by partial matching of link text

Shown below is the usage of find_element_by_partial_link_text()and find_elements_by_class_name()where the element is searched for on the URL page under test.

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
from time import sleep
from selenium.common.exceptions import NoSuchElementException

driver = webdriver.Firefox()
driver.get("https://www.***.com")

try:
    element = driver.find_element_by_partial_link_text("START TESTING")
    print("元素找到了")
    element = driver.find_elements_by_class_name('home-btn-2')
    print(“按钮找到了”)
except NoSuchElementException:
    print("元素没找到")
    
sleep(10)
driver.close()

HTML source code of WebElement

innerHTMLAttributes can be used to capture WebPagesource code. innerHTMLAlso used to check for any changes in the page since it was first loaded by the web browser . You can file the entire source code .htmlfor future reference.

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
from time import sleep
import io

driver = webdriver.Firefox()
driver.get("https://www.***.com")

elem = driver.find_element_by_xpath("//*")
source_code = elem.get_attribute("innerHTML")

filename = open('page_source.html', 'w')
filename.write(source_code)
filename.close()
    
sleep(10)

driver.close()

mouseover

In some cases, you may need to click on an item that is part of a menu or that is part of a multilevel menu. First, we find the menu item and perform a click on the desired menu item.

In the example below, after navigating to the Automation tab on the home page. The first task is to find an element in the Menu. By using the inspect tool, we can get the correct element-id, details as shown in the snapshot:

We move_to_element()move to the menu using an action, which is action_chainspart of the module. The next task is to find Automationthe menu item that contains the text, which we will use find_element_by_xpath(“//a[contains(text(),'Automation')]”)))to click.

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from time import sleep
    
driver = webdriver.Firefox()
driver.get("https://www.***.com")

action = ActionChains(driver);

parent_level_menu = driver.find_element_by_id("bs-example-navbar-collapse-1")
action.move_to_element(parent_level_menu).perform()

child_level_menu = driver.find_element_by_xpath("//a[contains(text(),'Automation')]")
child_level_menu.click();

sleep(10)

driver.close()

close the tab instead of the browser

One of the most basic yet essential tricks for any test automation Selenium script is to realize how to close a tab without closing the entire browser. driver.close()Closing the current tab driver.quit()will close all tabs (of the browser) and exit the driver. If you need to keep the browser window open (and quit all other tabs), you can use switch_to.window()the method, which takes an input parameter of window handle-id.

  • Note: There are other ways to solve this problem. window.open()method can be used with appropriate options (e.g. open new window, open new tab, etc.). send_keys()It is possible to send the correct key combination with using , but the behavior is geckodriverversion dependent (for Firefox), chromedriverversion, etc. Therefore, send_keys()approach is not advisable as the output will vary depending on the WebDriver version.

In the example below we open a new window containing the test URL and then close the other windows. We only use window_handlesto meet the requirements.

from selenium import webdriver
import time
 
driver = webdriver.Firefox()
driver.get('https://www.google.com')
# 打开新窗口
driver.execute_script("window.open('');")
time.sleep(5)
# 切换窗口
driver.switch_to.window(driver.window_handles[1])
driver.get("https://***.com")
time.sleep(5)
# 关闭
driver.close()
time.sleep(5)
# 切换回就窗口
driver.switch_to.window(driver.window_handles[0])
driver.get("https://www.***.com")
time.sleep(5)
# 关闭窗口
#driver.close()

Handle the dropdown menu

There is a requirement that a specific option must be selected from a drop down menu on the web page. You can select the desired option from the drop-down menu in several ways.

  • select_by_index (expected index value)

  • select_by_visible_text("text information")

  • select_by_value(value)

Before we select the desired element from the drop-down menu, it is very important to get the ID of the element under test. We use find_element_by_xpath()the method to locate the element, and once the element is found (using the ID), we select the value from the dropdown.

In the example below we show the different ways an element can be selected from a menu ( @ aria-label ='select')

from selenium import webdriver
from selenium.webdriver.support.ui import Select
from time import sleep
from selenium.common.exceptions import NoSuchElementException
from pip._vendor.distlib import resources

driver = webdriver.Firefox()
driver.get("http://demos.*****/test_Menu.html")

sleep(5)

try:
    select_element = Select(driver.find_element_by_xpath("//select[@aria-label='select']"))
    select_element.select_by_visible_text("bleed through")
    sleep(5)
    select_element.select_by_index(0)
    sleep(5)
except NoSuchElementException:
    print("元素查找失败")

sleep(5)

driver.quit()

checkbox handling

Checkboxes are a common element in web pages and are used in situations where you must select only one option out of several. Like the dropdown menu handling, we use find_element_by_xpath()methods to find the desired checkbox, and once we find the checkbox, we perform the click action.

We will use Selenium to automate the tests and check the box. Use driver.find_elements_by_xpath(“//*[contains(text(),'文本')]”)to complete the operation.

from selenium import webdriver
from selenium.webdriver.support.ui import Select
from time import sleep
from selenium.common.exceptions import NoSuchElementException
from pip._vendor.distlib import resources

driver = webdriver.Firefox()
driver.get("http://demos.***test_CheckBox.html")

sleep(5)

try:
    driver.find_element_by_xpath("//*[contains(text(), 'cb7: normal checkbox')]").click()
except NoSuchElementException:
    print("元素查找失败")

sleep(5)

driver.quit()

Select elements with CSS selectors

When performing test automation with Selenium, CSS locators can be used to locate elements on a web page. find_elements_by_css_selector()Can be used to target elements where the details of the element to be located (label, link, id, etc.) must be passed as an input parameter. It does this by CSS Selectorfinding the list of elements in the child elements of that element.

The purpose is to use find_elements_by_css_selector()find the "login" button on https://***.com/ and perform the click action. The code related to login is as follows. The code inspection tool snapshot also provides the required information.

<html>
........
<li class="login">
<a href="https://accounts.***.com/register">Free Sign Up</a>
</li>
.....
</html>

So we'll li.loginpass as an argument to find_elements_by_css_selector(), the action to be performed once the element is found Click.

from selenium import webdriver
from selenium.webdriver.support.ui import Select
from time import sleep
from selenium.common.exceptions import NoSuchElementException
from pip._vendor.distlib import resources

driver = webdriver.Firefox()
driver.get("https://www.***.com/")

sleep(5)

try:
    driver.find_element_by_css_selector("li.login").click()
except NoSuchElementException:
    print("Element not found")

sleep(5)

driver.quit()

 

Summarize:

Thanks to everyone who read my article carefully! ! !

I personally sorted out some technical materials I have compiled in my software testing career in the past few years, including: e-books, resume modules, various job templates, interview books, self-study projects, etc. Welcome everyone to click on the business card below to get it for free, don't miss it.

   Python automated testing learning exchange group: a full set of automated testing interview resume learning materials to obtain Click the link to join the group chat [python automated testing exchange]: http://qm.qq.com/cgi-bin/qm/qr?_wv=1027&k=DhOSZDNS -qzT5QKbFQMsfJ7DsrFfKpOF&authKey=eBt%2BF%2FBK81lVLcsLKaFqnvDAVA8IdNsGC7J0YV73w8V%2FJpdbby66r7vJ1rsPIifg&noverify=0&group_code=198408628

 

Guess you like

Origin blog.csdn.net/MXB_1220/article/details/131480378