使用Selenium WebDriver测试自动化的22条实用技巧
使用Selenium進(jìn)行測試自動(dòng)化已使全球的網(wǎng)站測試人員能夠輕松執(zhí)行自動(dòng)化的網(wǎng)站測試。 Webdriver是Selenium框架的核心組件,通過它您可以針對不同類型的瀏覽器(例如Google Chrome,Mozilla Firefox,Safari,Opera,Internet Explorer,Microsoft Edge等)對網(wǎng)站或Web應(yīng)用程序執(zhí)行自動(dòng)跨瀏覽器測試 。
與其他Web自動(dòng)化工具/框架相比,使用Selenium Webdriver執(zhí)行測試自動(dòng)化的主要優(yōu)勢是支持多種編程語言,例如Python,Java,C#,Ruby,PHP,JavaScript,.Net,Perl等。是Selenium WebDriver自動(dòng)化測試的基礎(chǔ)知識,然后您可以查看我們的Selenium WebDriver自動(dòng)化跨瀏覽器測試教程,在此我們討論Selenium的總體體系結(jié)構(gòu)以及如何將該框架與流行的編程語言一起使用。 您還可以查看我以前在Selenium Grid設(shè)置教程中進(jìn)行的跨瀏覽器測試文章 ,以利用Selenium進(jìn)行并行測試的能力。 無論使用哪種編程語言,都有某些最佳實(shí)踐適用于使用Selenium Webdriver(獨(dú)立于開發(fā)語言)執(zhí)行測試自動(dòng)化。
在本文中,我將與您分享一些Selenium自動(dòng)化測試的關(guān)鍵技巧,這些技巧涉及代碼優(yōu)化,性能改進(jìn),動(dòng)態(tài)網(wǎng)頁加載,處理CSS和HTML代碼等方面。
注 –這些用于Selenium WebDriver的自動(dòng)化測試的編碼技巧中的大多數(shù)都是通用的,并且可以與開發(fā)測試腳本所使用的編程語言無關(guān)地應(yīng)用。 但是,為了進(jìn)行下面的演示,我們將Selenium與Python語言結(jié)合使用。
Selenium技巧1 –設(shè)置Selenium Webdriver的可執(zhí)行路徑
為了與被測瀏覽器進(jìn)行通信,您需要首先從其官方網(wǎng)站下載相應(yīng)的插件/ webdriver。 該插件將負(fù)責(zé)與瀏覽器進(jìn)行通信,并且該插件應(yīng)存在于您正在開發(fā)測試的計(jì)算機(jī)上。 插件/ webdriver路徑必須在Selenium Webdriver配置中設(shè)置。
盡管可以將插件/ Webdriver放置在任何位置,因?yàn)槟梢栽赟elenium Webdriver配置中提供靜態(tài)/相對路徑,但是這種方法容易出錯(cuò),并且需要跟蹤文件路徑。 更好和更可靠的方法是將相應(yīng)的Selenium Webdriver放置在驅(qū)動(dòng)程序可執(zhí)行文件所在的位置,在這種情況下,您無需在Selenium Webdriver配置中指定可執(zhí)行文件路徑。
如果geckodriver在瀏覽器位置中不存在,則需要在源代碼中手動(dòng)添加相同的路徑。 我們導(dǎo)入selenium.webdriver.firefox.firefox_binary模塊以提供Firefox可執(zhí)行文件的路徑。
from selenium import webdriver from selenium.webdriver.firefox.firefox_binary import FirefoxBinaryff_binary = FirefoxBinary('path/to/gecko driver') browser = webdriver.Firefox(firefox_binary=ff_binary)如下面的代碼片段所示,由于壁虎驅(qū)動(dòng)程序(Firefox Webdriver)放置在與Firefox瀏覽器相同的位置,因此我們未指定其位置。 與前一種方法相比,這是一種更可靠的方法,可以幫助減少使用Selenium實(shí)現(xiàn)測試自動(dòng)化時(shí)的基本錯(cuò)誤。
''' Import the required modules for development ''' from selenium import webdriver from selenium.webdriver.common.keys import Keys from time import sleep'''Creation of Firefox Webdriver ''' driver = webdriver.Firefox() driver.get("https://www.lambdatest.com/")Selenium技巧2 –使用Selenium WebDriver捕獲測試自動(dòng)化的屏幕截圖
在執(zhí)行測試時(shí),您會(huì)遇到一些要求,其中必須捕獲屏幕快照以驗(yàn)證測試結(jié)果。 Selenium WebDriver提供了三種API,您可以通過它們獲取網(wǎng)頁的屏幕截圖。
前兩個(gè)API可讓您將當(dāng)前窗口的屏幕保存為.png文件。 如果存在IOError,則API返回False,否則返回True。 僅當(dāng)文件擴(kuò)展名為.png時(shí),這些API才有效,否則Python會(huì)引發(fā)錯(cuò)誤并且保存的內(nèi)容可能無法查看。 如果您希望以二進(jìn)制格式捕獲當(dāng)前窗口的屏幕,請使用get_screenshot_as_png()API。
''' Import the required modules for development ''' from selenium import webdriver import StringIO from PIL import Image'''Creation of Firefox Webdriver ''' driver = webdriver.Firefox() driver.get("https://www.lambdatest.com/")'''Taking screenshot of the web-page. File would be saved in the location where the source code is present ''''''Option - 1''' driver.save_screenshot('screenshot_1.png');'''Option - 2''' driver.get_screenshot_as_file('screenshot_2.png'); '''Option - 3''' screenshot = driver.get_screenshot_as_png();screenshot_size = (20, 10, 480, 600) image = Image.open (StringIO.StringIO(screen)) region = image.crop(screenshot_size) region.save('screenshot_3.jpg', 'JPEG', optimize=True)Selenium技巧3 –使用Selenium WebDriver進(jìn)行自動(dòng)化測試時(shí)刷新網(wǎng)頁
在某些情況下,可能需要刷新網(wǎng)頁,尤其是在等待特定條件時(shí)。 使用Selenium Webdriver執(zhí)行測試自動(dòng)化時(shí),有多種方法可以刷新網(wǎng)頁,下面列出了一種流行的方法。
1. driver.refresh()方法
顧名思義, refresh()方法用于刷新網(wǎng)頁。 因此,它本質(zhì)上是異步的。 您應(yīng)該將此API與document.readyState()結(jié)合使用。
''' Import the required modules for development ''' from selenium import webdriver'''Creation of Firefox Webdriver ''' driver = webdriver.Firefox() driver.get("https://www.lambdatest.com/") driver.refresh()2. ActionChains()方法
ActionChains()是自動(dòng)化與Selenium進(jìn)行自動(dòng)化測試的低級交互的另一種方式,例如按鍵,鼠標(biāo)按鈕動(dòng)作等。為了刷新網(wǎng)頁,我們使用了'CTRL + F5'組合。
import time from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.keys import Keys'''Creation of Firefox Webdriver ''' # driver = webdriver.Chrome() driver = webdriver.Firefox() driver.get("https://www.lambdatest.com/")time.sleep(5)print("Before refresh")ActionChains(driver) \.key_down(Keys.CONTROL) \.send_keys(Keys.F5) \.key_up(Keys.CONTROL) \.perform()print("After refresh")sleep(5) driver.quit()Selenium技巧4 –在新標(biāo)簽頁中打開網(wǎng)頁
execute_script可用于在當(dāng)前窗口/框架中同步執(zhí)行JavaScript代碼。 將打開網(wǎng)頁的參數(shù)(JavaScript)作為參數(shù)傳遞給execute_script
from selenium import webdriver from selenium.webdriver.common.keys import Keys from time import sleepdriver = webdriver.Firefox() driver.get("http://www.google.com/")driver.implicitly_wait(10)#open tab driver.execute_script("window.open('https://www.lambdatest.com', 'new tab')")sleep(5) driver.quit()Selenium技巧5 –保存網(wǎng)頁的部分屏幕截圖
在某些情況下,使用Selenium執(zhí)行測試自動(dòng)化時(shí),可能需要截取網(wǎng)頁的部分屏幕截圖。 在這種情況下,您可以使用枕頭模塊。 您需要先使用以下命令安裝Pillow / PIL模塊
pip install pillow
使用get_screenshot_as_png() API拍攝整個(gè)網(wǎng)頁的屏幕截圖。 截圖準(zhǔn)備好后,將使用PIL庫在內(nèi)存中打開捕獲的圖像,然后裁剪圖像(包含整個(gè)網(wǎng)頁的屏幕截圖)以獲取結(jié)果圖像。
from selenium import webdriver ''' Install the Pillow module using the command pip install pillow ''' from PIL import Image from io import BytesIOdriver = webdriver.Firefox() driver.get('http://google.com/')# Use the Inspection tool to find the location of the logo element = driver.find_element_by_id('hplogo') image_location = element.location size = element.sizepng = driver.get_screenshot_as_png()''' Since the webpage screenshot is ready, we can exit the browser.''' driver.quit()''' PIL Library is used to open the image in memory ''' crop_image = Image.open(BytesIO(png))''' Extract the Left, Right, Top, and Bottom co-ordinates ''' left = image_location['x'] top = image_location['y'] right = image_location['x'] + size['width'] bottom = image_location['y'] + size['height']crop_image = crop_image.crop((left, top, right, bottom)) crop_image.save('logo-screenshot.png')Selenium技巧6 –執(zhí)行JavaScript代碼
當(dāng)您使用Selenium WebDriver執(zhí)行測試自動(dòng)化時(shí),execute_script用于執(zhí)行JavaScript代碼。 語法為driver.execute_script(“此處JavaScript代碼”) 。
如下例所示,執(zhí)行Register的on_click操作[類名是home-cta]。
from selenium import webdriver from time import sleepdriver = webdriver.Firefox() driver.get("https://www.lambdatest.com")driver.execute_script("document.getElementsByClassName('home-cta')[0].click()")sleep(10)driver.close()硒技巧#7 –提取JavaScript代碼的結(jié)果
調(diào)用JavaScript代碼以使用Selenium進(jìn)行自動(dòng)化測試后,您需要提取這些JavaScript代碼的結(jié)果。 您可以使用return關(guān)鍵字來獲取JavaScript代碼的結(jié)果,如我們在解釋JavaScript的擴(kuò)展示例中所示。
from selenium import webdriver from time import sleepdriver = webdriver.Firefox() driver.get("https://www.lambdatest.com")driver.execute_script("document.getElementsByClassName('home-cta')[0].click()")result = driver.execute_script("return 0") print(result)sleep(10)driver.close()Selenium技巧8 –處理多種瀏覽器類型以進(jìn)行自動(dòng)跨瀏覽器測試
您可能需要在多種情況下針對不同的瀏覽器(例如Firefox,Chrome,Internet Explorer)測試代碼。 跨不同瀏覽器測試網(wǎng)站的做法稱為自動(dòng)瀏覽器測試 。 要使用Selenium自動(dòng)化測試執(zhí)行自動(dòng)瀏覽器測試,您應(yīng)該在單元測試代碼或pytest代碼中合并對這些瀏覽器的選擇性處理。 下面顯示了一個(gè)代碼片段(利用pytest)來處理多個(gè)瀏覽器:
# Import the 'modules' that are required for executionimport pytest from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.keys import Keys from time import sleep#Fixture for Firefox @pytest.fixture(params=["chrome", "firefox"],scope="class") def driver_init(request):if request.param == "chrome":# Perform necessary actions hereif request.param == "firefox":# Perform necessary actions hereyieldweb_driver.close()......................Selenium技巧9 –使用CSS定位器在網(wǎng)頁上定位元素
使用Selenium執(zhí)行測試自動(dòng)化時(shí),在頁面上定位Web元素是自動(dòng)化腳本的基礎(chǔ)。 如果您想基于特定種類的Web元素(如Tag,Class,ID等)的存在來執(zhí)行條件執(zhí)行,則可以使用find_elements _ *** API。 下面提到其中一些
- find_elements_by_class_name –按類名稱查找元素
- find_elements –按策略和定位器查找元素
- find_element_by_link_text –通過鏈接文本查找元素
- find_element_by_partial_link_text –通過鏈接文本的部分匹配來查找元素
下面顯示的是find_element_by_partial_link_text和find_elements_by_class_name的用法,其中在受測試的URL https://www.lambdatest.com/上搜索了元素。
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 NoSuchElementExceptiondriver = webdriver.Firefox() driver.get("https://www.lambdatest.com")try:element = driver.find_element_by_partial_link_text("START TESTING")print("Partial text Element found")element = driver.find_elements_by_class_name('home-btn-2')print("Button Element found") except NoSuchElementException:print("No element found")sleep(10) driver.close()查看我們的博客系列,詳細(xì)了解用于Selenium測試自動(dòng)化的各種CSS定位器。
硒技巧#10 – WebElementHTML源
innerHTML屬性可用于捕獲WebPage的源代碼。 自頁面首次由網(wǎng)絡(luò)瀏覽器加載以來,innerHTML還用于檢查頁面中的任何更改。 您可以將整個(gè)源代碼編寫為.html文件,以備將來參考。
from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.keys import Keys from time import sleep import iodriver = webdriver.Firefox() driver.get("https://www.lambdatest.com")elem = driver.find_element_by_xpath("//*") source_code = elem.get_attribute("innerHTML")filename = open('lambdatest_page_source.html', 'w') filename.write(source_code) filename.close()sleep(10)driver.close()硒提示11 –將鼠標(biāo)懸停在動(dòng)作上
在某些情況下,您可能需要單擊作為菜單一部分的項(xiàng)目或作為多級菜單一部分的項(xiàng)目。 首先,我們找到菜單項(xiàng),然后在所需的菜單項(xiàng)上執(zhí)行單擊操作。
在下面的示例中,被測URL為https://www.lambdatest.com/ 。 目的是導(dǎo)航到主頁上的“ 自動(dòng)化”選項(xiàng)卡 。 第一個(gè)任務(wù)是找到與ID bs-example-navbar-collapse-1匹配的Menu。 通過使用檢查工具,我們可以獲得正確的element-id,詳細(xì)信息如快照中所示
我們使用move_to_element操作移動(dòng)到菜單,該操作是action_chains模塊的一部分。 下一個(gè)任務(wù)是找到包含文本“ Automation”的菜單項(xiàng),我們將使用find_element_by_xpath(“ // a [contains(text(),'Automation')]”)))進(jìn)行單擊操作。
from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains from time import sleepdriver = webdriver.Firefox() driver.get("https://www.lambdatest.com")action = ActionChains(driver);# Head on the top-level menu on Lambdatest website parent_level_menu = driver.find_element_by_id("bs-example-navbar-collapse-1") action.move_to_element(parent_level_menu).perform()# Perform a click operation on the Menu item which contains text Automation child_level_menu = driver.find_element_by_xpath("//a[contains(text(),'Automation')]") child_level_menu.click();sleep(10)driver.close()Selenium Tip#12 –關(guān)閉標(biāo)簽而不關(guān)閉瀏覽器
對于任何測試自動(dòng)化Selenium腳本,最基本但必不可少的技巧之一是實(shí)現(xiàn)如何在不關(guān)閉整個(gè)瀏覽器的情況下關(guān)閉選項(xiàng)卡。 driver.close()關(guān)閉焦點(diǎn)選項(xiàng)卡, driver.quit()將關(guān)閉(瀏覽器的)所有選項(xiàng)卡,并退出驅(qū)動(dòng)程序。 如果需要使瀏覽器窗口保持打開狀態(tài)(并退出所有其他選項(xiàng)卡),則可以使用switch_to.window方法,該方法的輸入?yún)?shù)為window handle-id 。
注 –還有其他方法可以解決此問題。 window.open方法可以與適當(dāng)?shù)倪x項(xiàng)一起使用(例如,打開新窗口,打開新選項(xiàng)卡等)。 可以使用使用send_keys發(fā)送正確的按鍵組合,但是該行為取決于geckodriver版本(對于Firefox),chromedriver版本等。因此, send_keys方法不是可取的,因?yàn)檩敵鰰?huì)根據(jù)WebDriver版本而有所不同。
在下面的示例中,我們打開一個(gè)包含測試URL的新窗口,然后關(guān)閉其他窗口。 我們僅使用window_handles來達(dá)到要求。
from selenium import webdriver import timedriver = webdriver.Firefox() driver.get('https://www.google.com') # Open a new window driver.execute_script("window.open('');") time.sleep(5) # Switch to the new window since the focus would still be on the old window driver.switch_to.window(driver.window_handles[1]) driver.get("https://lambdatest.com") time.sleep(5) # close the active tab driver.close() time.sleep(5) # Switch back to the first tab driver.switch_to.window(driver.window_handles[0]) driver.get("https://www.yahoo.com") time.sleep(5) # Close the only tab, will also close the browser. #driver.close()Selenium Tip#13 –處理頁面中的下拉菜單
有一個(gè)要求,您必須從網(wǎng)頁上的下拉菜單中選擇一個(gè)特定的選項(xiàng)。 您可以通過多種方式從下拉菜單中選擇所需的選項(xiàng)。
- select_by_index(期望的索引值)
- select_by_visible_text(“ text_to_be_selected_from_drop_down_menu”)
- select_by_value(值)
我們將根據(jù)此要求使用http://demos.dojotoolkit.org/dijit/tests/test_Menu.html進(jìn)行Selenium自動(dòng)化測試。 在我們從下拉菜單中選擇所需元素之前,獲取被測元素的ID非常重要。 我們使用find_element_by_xpath方法來定位該元素,并且一旦找到該元素(使用ID),便從下拉菜單中選擇該值。
在下面的示例中,我們顯示了可以從菜單中選擇元素的不同方法( @ 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 resourcesdriver = webdriver.Firefox() driver.get("http://demos.dojotoolkit.org/dijit/tests/test_Menu.html")''' Let the page load completely ''' sleep(5)try:''' You can derive these details by using Web Inspector '''select_element = Select(driver.find_element_by_xpath("//select[@aria-label='select']"))# Option 1 - Selecting the drop-down item by using the textselect_element.select_by_visible_text("bleed through")sleep(5)# Option 2 - Selecting the drop-down item by using the index valueselect_element.select_by_index(0)sleep(5)# Option 3 - Selection of desired option using value''' This option would fail since there is no value in the pagewhich we are testing right now ''' # select_element.select_by_value('2') except NoSuchElementException:print("Element not found")''' Addition of delay so that we can have a look at the output ''' sleep(5)''' Release the resources ''' driver.quit()硒技巧14 –使用復(fù)選框處理操作
復(fù)選框是網(wǎng)頁中的常見元素,用于您僅需從多個(gè)選項(xiàng)中選擇一個(gè)選項(xiàng)的情況下。 像下拉菜單處理一樣,我們使用find_element_by_xpath方法找到所需的復(fù)選框,一旦找到該復(fù)選框,就會(huì)執(zhí)行單擊操作。
我們將使用http://demos.dojotoolkit.org/dijit/tests/form/test_CheckBox.html進(jìn)行Selenium自動(dòng)化測試,并且要求“選中”值為cb7的復(fù)選框:“正?!睆?fù)選框。 使用driver.find_elements_by_xpath(“ // * [contains(text(),'要搜索的文本')]”)完成匹配。
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 resourcesdriver = webdriver.Firefox() driver.get("http://demos.dojotoolkit.org/dijit/tests/form/test_CheckBox.html")''' Let the page load completely ''' sleep(20)try:''' You can derive these details by using Web Inspector '''driver.find_element_by_xpath("//*[contains(text(), 'cb7: normal checkbox')]").click() except NoSuchElementException:print("Element not found")''' Addition of delay so that we can have a look at the output ''' sleep(5)''' Release the resources ''' driver.quit()Selenium Tip#15 –通過CSS選擇器選擇元素
在使用Selenium執(zhí)行測試自動(dòng)化時(shí),可以使用CSS定位器來定位網(wǎng)頁上的元素。 find_elements_by_css_selector可以用于定位必須將要定位的元素詳細(xì)信息(標(biāo)簽,鏈接,ID等)作為輸入?yún)?shù)傳遞的元素。 它通過CSS Selector在該元素的子元素中找到元素列表。
目的是使用find_elements_by_css_selector在https://lambdatest.com/上找到“登錄”按鈕并執(zhí)行單擊操作。 與登錄相關(guān)的代碼如下。 代碼檢查工具快照還提供了所需的信息。
<html> ........ <li class="login"> <a href="https://accounts.lambdatest.com/register">Free Sign Up</a> </li> ..... </html>因此,我們將li.login作為參數(shù)傳遞給find_element_by_css_selector,一旦找到元素,就執(zhí)行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 resourcesdriver = webdriver.Firefox() driver.get("https://www.lambdatest.com/")''' Let the page load completely ''' sleep(20)try:''' You can derive these details by using Web Inspector '''driver.find_element_by_css_selector("li.login").click() except NoSuchElementException:print("Element not found")''' Addition of delay so that we can have a look at the output ''' sleep(5)''' Release the resources ''' driver.quit()不要忘記閱讀我們有關(guān)將CSS選擇器用于Selenium進(jìn)行自動(dòng)化測試的綜合文章。
Selenium Tip#16 –明確等待處理不同的情況
在Selenium自動(dòng)化測試中觀察到一種情況是很正常的,在這種情況下,網(wǎng)頁可能需要花費(fèi)一些時(shí)間來加載,或者您希望在觸發(fā)測試代碼之前可以看到頁面上的特定Web元素。 在這種情況下,您需要執(zhí)行“ 顯式等待” ,這是一段代碼,通過它可以定義要發(fā)生的條件,然后再繼續(xù)執(zhí)行代碼。
Selenium具有WebDriverWait ,可以將其應(yīng)用于任何具有條件和持續(xù)時(shí)間的Web元素。 如果不存在執(zhí)行等待的元素或發(fā)生超時(shí),則可能引發(fā)異常。
在下面的示例中,我們等待link_text'Sitemap'加載到頁面上,并在WebDriverWait方法中指定了超時(shí)。 如果在超時(shí)時(shí)間內(nèi)未加載該元素,則拋出異常。
from selenium import webdriver from selenium.common.exceptions import TimeoutException from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.common.by import By from pip._vendor.distlib import resources from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as ECdriver = webdriver.Firefox() driver.get("https://www.lambdatest.com/") timeout = 10try:''' We wait till the time link with text SITEMAP is loaded '''''' If that link text is not present on the page, it gives a time out '''''' Try replacing Sitemap with Sitemap123 and you can encounter a timeout '''element_present = EC.presence_of_element_located((By.LINK_TEXT, 'Sitemap'))WebDriverWait(driver, timeout).until(element_present) except TimeoutException:print("Timed out while waiting for page to load") driver.quit()Selenium Tip #17 – Scroll Operations In A Web Page在使用Selenium執(zhí)行測試自動(dòng)化時(shí),您可能需要在頁面上執(zhí)行上滾/下滾操作的要求。 您可以將execute_script與window.scrollTo JS代碼用作參數(shù)來實(shí)現(xiàn)相同的效果。 在下面的示例中,加載被測網(wǎng)站后,我們滾動(dòng)到頁面的末尾。
from selenium import webdriver from time import sleepdriver = webdriver.Firefox() driver.get("https://www.lambdatest.com/") timeout = 10''' Scroll to the end of the page ''' driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")''' Sleep is added so that you can have a look at the output ''' sleep(10)''' Scroll again to the top of the page ''' driver.execute_script("window.scroll(0, 0);")sleep(10) driver.quit()Selenium Tip#18 –使用Selenium放大和縮小
為了在進(jìn)行Selenium自動(dòng)化測試時(shí)放大或縮小,應(yīng)使用transform CSS屬性 (適用于相應(yīng)的瀏覽器),該屬性可讓您在頁面上執(zhí)行放大,縮小,旋轉(zhuǎn),傾斜等操作。
不同類型的瀏覽器CSS參數(shù)如下
在下面的示例中,我們將瀏覽器中加載的網(wǎng)頁縮小200%,然后再放大100%(即恢復(fù)正常)。 由于我們使用的是Firefox瀏覽器,因此我們使用了MozTransform CSS屬性。
from selenium import webdriver from time import sleepdriver = webdriver.Firefox() driver.get("https://www.lambdatest.com/") timeout = 10''' Zoom in by 200% ''' driver.execute_script('document.body.style.MozTransform = "scale(2.0)";') driver.execute_script('document.body.style.MozTransformOrigin = "0 0";')sleep(10)''' Zoom out by 100% '''driver.execute_script('document.body.style.MozTransform = "scale(1.0)";') driver.execute_script('document.body.style.MozTransformOrigin = "0 0";')''' Sleep is added so that you can have a look at the output ''' sleep(10)''' Release all the resources ''' driver.quit()硒技巧#19 –在網(wǎng)頁中查找元素的大小
您必須首先通過ID搜索元素,然后使用.size屬性來計(jì)算搜索到的元素的大小。 在下面的示例中,我們在頁面http://demos.dojotoolkit.org/dijit/tests/test_Menu.html中計(jì)算按鈕create_programmatic_menu(ID = createDestoryButton)的大小。
from selenium import webdriver from time import sleepdriver = webdriver.Firefox() driver.get("http://demos.dojotoolkit.org/dijit/tests/test_Menu.html") timeout = 10search_element = driver.find_element_by_id("createDestroyButton")print(search_element.size)''' Release all the resources ''' driver.quit()當(dāng)您執(zhí)行上述代碼時(shí),它將輸出按鈕的大小(ID – CreateDestroyButton)。
Selenium技巧#20 –獲取網(wǎng)頁中元素的X和Y坐標(biāo)
您必須遵循用于計(jì)算元素大小的類似方法。 您必須首先通過ID搜索元素,然后使用.location屬性來計(jì)算搜索到的元素的X和Y坐標(biāo)。
測試URL為http://demos.dojotoolkit.org/dijit/tests/test_Menu.html ,我們計(jì)算按鈕create_programmatic_menu(ID = createDestoryButton)的X和Y坐標(biāo)
from selenium import webdriver from time import sleepdriver = webdriver.Firefox() driver.get("http://demos.dojotoolkit.org/dijit/tests/test_Menu.html") timeout = 10search_element = driver.find_element_by_id("createDestroyButton")print(search_element.location)''' Release all the resources ''' driver.quit()當(dāng)您執(zhí)行上述代碼時(shí),它將輸出按鈕(ID – CreateDestroyButton)的X,Y坐標(biāo)e。
Selenium提示#21 –使用自定義配置文件禁用JavaScript
如果要禁用瀏覽器JavaScript支持以驗(yàn)證自動(dòng)跨瀏覽器與Selenium自動(dòng)化測試的兼容性,則需要更改被測瀏覽器的配置文件設(shè)置(在本例中為Firefox),并將更改應(yīng)用于配置文件。 我們使用DEFAULT_PREFERENCES ['frozen'] ['javascript.enabled'] = False禁用瀏覽器JavaScript支持。
執(zhí)行代碼后,您應(yīng)該通過在地址欄中輸入about:config并搜索javascript.enabled屬性的值來驗(yàn)證配置文件的更改。
from selenium import webdriver''' Since we have the geckodriver & Firefox browser in same location ''' ''' We do not pass the location of the Firefox profile ''' ff_profile = webdriver.FirefoxProfile()ff_profile.DEFAULT_PREFERENCES['frozen']['javascript.enabled'] = False ff_profile.set_preference("app.update.auto", False) ff_profile.set_preference("app.update.enabled", False)''' Update the preferences ''' ff_profile.update_preferences()''' Load the Firefox browser with the updated profile ''' driver = webdriver.Firefox(ff_profile)''' Verify whether the changes are working fine or not ''' driver.get("about:config")下面是Firefox中about:config設(shè)置的屏幕截圖(代碼執(zhí)行后)
Selenium提示#22 –設(shè)置手動(dòng)代理設(shè)置
在某些情況下,您可能需要更改代理設(shè)置才能執(zhí)行測試。 要更改代理設(shè)置,需要首先導(dǎo)入模塊selenium.webdriver.common.proxy 。 您必須將代理類型設(shè)置為MANUAL ,然后更改代理設(shè)置,然后將新設(shè)置應(yīng)用到被測瀏覽器(在我們的示例中為Firefox)。
您需要用計(jì)劃用于測試的IP地址和端口號替換ip_address和port_number。
from selenium import webdriver from selenium.webdriver.common.proxy import Proxy, ProxyTypeproxy_settings = Proxy()''' The proxy settings are first changed to Manual ''' proxy_settings.proxy_type = ProxyType.MANUAL''' Replace ip_address with Proxy IP address and ''' ''' port_number with the port number which you plan to use ''' proxy_settings.http_proxy = "ip_address:port_number" proxy_settings.socks_proxy = "ip_address:port_number" proxy_settings.ssl_proxy = "ip_address:port_number"''' You can add capabilties for different browsers & devices ''' capabilities = webdriver.DesiredCapabilities.FIREFOX proxy_settings.add_to_capabilities(capabilities)driver = webdriver.Firefox(desired_capabilities=capabilities)結(jié)論
我們涵蓋了大多數(shù)Selenium技巧,可幫助您像專業(yè)人員一樣使用Selenium進(jìn)行測試自動(dòng)化。 盡管您可以使用本地計(jì)算機(jī)在不同的瀏覽器,設(shè)備和操作系統(tǒng)上驗(yàn)證您的網(wǎng)站/網(wǎng)絡(luò)應(yīng)用程序,但是由于您無法涵蓋設(shè)備+操作系統(tǒng)+瀏覽器(及瀏覽器版本)的全部范圍,因此測試的范圍將受到限制。 在這里,您應(yīng)該利用這些提示和技巧對網(wǎng)站/ Web應(yīng)用程序執(zhí)行自動(dòng)跨瀏覽器測試。
當(dāng)您開始通過在超過2000種真實(shí)的瀏覽器+ OS +設(shè)備組合上測試Web應(yīng)用程序來擴(kuò)展測試范圍時(shí),必須進(jìn)行最小的更改才能將本地Selenium自動(dòng)化測試代碼移至LambdaTest 云上Selenium Grid 。 您還可以集成到許多CI CD工具,項(xiàng)目管理工具等。
使用Selenium進(jìn)行測試自動(dòng)化可能是一項(xiàng)艱巨的任務(wù),但是要獲得可行的見解,我在本文上面列出了一些有關(guān)Selenium自動(dòng)化測試的實(shí)用技巧。 您可以精通Selenium中的測試自動(dòng)化。 讓我知道是否還有其他有關(guān)使用Selenium進(jìn)行測試自動(dòng)化的技巧可以幫助您快速跟蹤測試周期。 干杯和快樂的測試!
翻譯自: https://www.javacodegeeks.com/2019/07/test-automation-selenium-webdriver.html
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的使用Selenium WebDriver测试自动化的22条实用技巧的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: (串口通信 linux)
- 下一篇: gta安卓手机版下载中文版(gta安卓手