skip to Main Content

I have created a bot to auto-update my product prices on Shopify with Selenium Python. I told this bot to locate the price_element clear it, and then send the new prices as a 2 decimal place formated string. e.g. 184.99.

 formatted_price = "{:.2f}".format(total_price)
 # Scroll down to the price element
 self.driver.find_element(By.TAG_NAME, 'body').send_keys(Keys.PAGE_DOWN)
 self.driver.find_element(By.TAG_NAME, 'body').send_keys(Keys.PAGE_DOWN)
 price_element = self.driver.find_element(By.XPATH, '//input[@name="price"]')                  
 price_element.clear()
 price_element.send_keys(formatted_price)

To my surprise, the bot was able to locate the element, but it couldn’t clear it and started adding new prices to the previous prices. The image below shows the previous prices of 162.99, 184.99, and 184.99 combined into the price box.
Image of combined prices

2

Answers


  1. Seems like a lot of code. Without knowing the rest of your code, how about something like this?

    from browserist import Browser
    
    # Other code goes here ...
    
    formatted_price = "{:.2f}".format(total_price)
    
    with Browser() as browser:
        browser.open.url("https://example.com")
        browser.scroll.into_view_if_not_in_viewport("//input[@name='price']")  # Instead of page down twice.
        browser.input.value("//input[@name='price']", formatted_price)
    

    In full disclosure, I’m the author of the Browserist package. Browserist is lightweight, less verbose extension of the Selenium web driver that makes browser automation even easier. Simply install the package with pip install browserist and you’re ready to go.

    Other notes:

    • Browserist always clears an input field before send a new value so you don’t have to worry about that with price_element.clear().
    • Browserist also supports log in methods if you need to add that to your automation flow.
    • Technically you don’t need to scroll down to add the input so you could drop the browser.scroll.into_view_if_not_in_viewport(...) line of code.
    Login or Signup to reply.
  2. From the looks of it, the effort to clear the price element is probably before it is fully loaded/ accessible. Perhaps you could add a wait condition to ensure the element is ready to be accessed before you attempt interacting with it.

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions
    # rest of your previous code
    # //
    wait = WebDriverWait(self.driver, 10)
    price_element = wait.until(EC.presence_of_element_located((By.XPATH, '//input[@name="price"]')))
    price_element.clear()
    price_element.send_keys(formatted_price)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search