Selenium Python Usage Tips

Book above and above:

Handle waiting in different situations

In elenium automated tests, a Web page may take some time to load, or you may want to see specific Web elements on the page before triggering the test code.In this case, you need to execute Explicit Wait, which is a piece of code that defines the conditions that will occur before you continue executing the code.

Selenium has WebDriverWait and can be applied to any Web element with conditions and durations.Exceptions may be thrown if there are no elements to perform the wait or if a timeout occurs.

In the following example, we wait for link_text=Sitemap to load onto the page and specify a timeout in the WebDriverWait method.If the element is not loaded within the timeout period, an exception is thrown.

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 EC

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

try:
    element_present = EC.presence_of_element_located((By.LINK_TEXT, 'Sitemap'))
    WebDriverWait(driver, timeout).until(element_present)
except TimeoutException:
    print("Find user timeout!")
driver.quit()

Scrolling in Web Pages

When using Selenium to perform test automation, you may need to perform a roll-up/roll-down requirement on the page.You can use execute_script() and window.scrollTo(JS) code as parameters to achieve the same effect.In the following example, after loading the website under test, we scroll to the end of the page.

from selenium import webdriver
from time import sleep

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

''' Scroll to End of Page'''
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

sleep(10)

''' Scroll to the top of the page'''
driver.execute_script("window.scroll(0, 0);")

sleep(10)
driver.quit()

Zoom in and out using Selenium

In order to zoom in or out during Selenium automated tests, you should use the transformCSS property (for the appropriate browser), which allows you to zoom in, zoom out, rotate, tilt, and so on, on the page.CSS parameters for different types of browsers are as follows

In the following example, we reduce the number of pages loaded in the browser by 200%, then zoom in by 100% (that is, return to normal).Since we are using the Firefox browser, we are using the MozTransform CSS property.

from selenium import webdriver
from time import sleep

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

''' Zoom in 200% '''
driver.execute_script('document.body.style.MozTransform = "scale(2.0)";')
driver.execute_script('document.body.style.MozTransformOrigin = "0 0";')

sleep(10)

''' Restore 100% '''

driver.execute_script('document.body.style.MozTransform = "scale(1.0)";')
driver.execute_script('document.body.style.MozTransformOrigin = "0 0";')

sleep(10)

driver.quit()

Find the size of an element

You must first search for elements by ID, then use the.Size attribute to calculate the size of the elements you search for.In the following example, we calculate the size of the button create_programmatic_menu(ID = createDestoryButton) on the page.

from selenium import webdriver
from time import sleep

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

search_element = driver.find_element_by_id("createDestroyButton")

print(search_element.size)

driver.quit()

Get the X and Y coordinates of an element

You must follow a similar method for calculating the size of elements.You must first search for elements by ID, then use the.location attribute to calculate the X and Y coordinates of the elements you search for.Calculates the X and Y coordinates of the button create_programmatic_menu(ID = createDestoryButton).

from selenium import webdriver
from time import sleep

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

search_element = driver.find_element_by_id("createDestroyButton")

print(search_element.location)

''' Release all the resources '''
driver.quit()

Disable JavaScript using custom profiles

If you want to disable JavaScript support for your browser to verify the compatibility of automated cross-browser and Selenium automated tests, you need to change the profile settings for the browser under test (Firefox in this case) and apply the changes to the profile.We use DEFAULT_PREFERENCES ['frozen'] ['javascript.enabled'] = False to disable browser JavaScript support.

After executing the code, you should verify the changes to the configuration file by typing about:config in the address bar and searching for the value of the javascript.enabled property.

from selenium import webdriver

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 Configuration '''
ff_profile.update_preferences()

''' Load Profile '''
driver = webdriver.Firefox(ff_profile)

''' Verify validity '''
driver.get("about:config")

Set up manual proxy settings

In some cases, you may need to change the proxy settings to perform the test.To change proxy settings, you first need to import the module selenium.webdriver.common.proxy.You must set the proxy type to MANUAL, then change the proxy settings, and apply the new settings to the browser under test (Firefox in our example).You need to replace ip_address and port_number with the IP address and port number that you plan to use for testing.

from selenium import webdriver
from selenium.webdriver.common.proxy import Proxy, ProxyType

proxy_settings = Proxy()

''' Modify Configuration '''
proxy_settings.proxy_type = ProxyType.MANUAL

proxy_settings.http_proxy = "ip_address:port_number"
proxy_settings.socks_proxy = "ip_address:port_number"
proxy_settings.ssl_proxy = "ip_address:port_number"

''' Add Certificate '''
capabilities = webdriver.DesiredCapabilities.FIREFOX
proxy_settings.add_to_capabilities(capabilities)

driver = webdriver.Firefox(desired_capabilities=capabilities)
  • Solemn statement: The article was first published under the public number FunTester, which prohibits third parties (except Tencent Cloud) from reproducing and publishing it.

Selected Technical Articles

Selected non-technical articles

Tags: Selenium Firefox Javascript Python

Posted on Fri, 07 Feb 2020 17:54:40 -0800 by Dillenger