How to monitor web's element is changed or not?

Question:

So I want to buy discounted stuff online,and the websites will let users buy it at certain time with limited amount , so I use selenium to write an automatic program.
and here’s a part of my code

while 1:
    start = time.clock()
    try:
        browser.find_element_by_class_name('SasCheckoutButton__mod___1BK9F.CheckoutBar__buyNowBtn___qgDtR.CheckoutBar__checkoutButton___jSkkJ').click()
        print ('located')
        end=time.clock()
        break
    except:
        print("not yet!")

My first idea is to use while to monitor if the button shows up yet ,so that if the button is updated by the website’s manager I can press it as soon as possible . but here’s the problem , if the web is updated,I don’t think I can press it without refreshing , right?(I actually don’t know how the engineer manage the web pages , I just guessing based on my experience) so I have to add refreshing in the while , but I think this will slow down the program a lot , so I am wondering if there’s any way in selenium to monitor the changing without refreshing? or maybe a more efficient way to add refreshing in the while? because I don’t think refreshing every time it can’t find the buy button is a good idea.

Asked By: chungchung

||

Answers:

What you can do to monitor how the whole thing works would something like this :

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

browser = ...
url = "..."
delay = 3 # seconds
classname = 'SasCheckoutButton__mod___1BK9F.CheckoutBar__buyNowBtn___qgDtR.CheckoutBar__checkoutButton___jSkkJ'

counter = 0
while True:
    counter += 1
    try:
        browser.get(url)
        if counter >= 10:
            break
        myElem = WebDriverWait(browser, delay).until(EC.presence_of_element_located((By.CLASS_NAME, classname)))
        print ('located')
        break
    except TimeoutException:
        print(f"reload #{counter}")

myElem.click()

Then you could check if you really need to refresh the webpage or if the page "self refreshes" (using something like scripts for example).

Answered By: tgrandje