Selenium code in PyCharm(Python) running slow, how to improve speed?

Viewed 650

I wrote this automated bot in PyCharm and I do not know why my code executes so slow? Any help for improvement is sincerely appreciated.

from selenium import webdriver
from InfoApp import keys
import time
def order(k):
    driver = webdriver.Chrome(executable_path='driver/chromedriver')
    driver.get(k['product_url'])
    driver.maximize_window()
    driver.find_element_by_xpath('//*[@id="RightRail"]/div/div[4]/fieldset/div/div[7]/label').click()
    driver.execute_script("window.scrollTo(0, 1000)")
    driver.find_element_by_xpath('//*[@id="floating-atc-wrapper"]/div/button').click()
    driver.find_element_by_xpath('//*[@id="PDP"]/div/div[4]/div/div/div/div/div/div/div/div/div/div[3]/div/button[2]').click()
    time.sleep(5)
    driver.find_element_by_xpath('//*[@id="nav-cart"]/a/div/span').click()
    driver.find_element_by_xpath('//*[@id="react-root"]/div/div[4]/button').click()
    driver.find_element_by_xpath('//*[@id="qa-guest-checkout"]').click()
    driver.find_element_by_xpath('//*[@id="firstName"]').send_keys(k["First_Name"])

if __name__ == '__main__':
    order(keys)
1 Answers

remove time.sleep and add explicit or implicit wait:

you can add implicit wait as

driver = webdriver.Chrome(executable_path='driver/chromedriver')
driver.implicitly_wait(10)

this will automatically make all commands to wait maximum of 10 seconds . If element not found in 10 sec then element not found is thrown.

but this will not check clicability , visibility etc , this checks only for presence of element. For other condition you can use explicit wait.

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

wait = WebDriverWait(browser, 10)

elem= wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, 'somelocator')))

Note:

There is good video link jeff added but to add to that :

implicit waits are not bad practices, mixing implicit wait and explicit wait is bad practice. As implict wait waits for only the presence of the elment so in most cases you cannot avoid explicit wait as you need to wait for visibility,clicability etc . so its better to avoid it completely as it cause long waits in your code when you mix both implicit and explicit wait together

So if you are using explicit wait DONT use implict wait

Related