Search code examples
pythonseleniumaverage

How to calculate average from webelement list?


I chose the price list from WebElements. How can I calculate the price average?

I try use len() and sum() but it's not working.

price = browser.find_elements(by=By.CSS_SELECTOR, value="p.sc-gKPRtg.sc-cTVMo.gFSBHP.dJSocd")
for i in price:
    value = i.text
    print(value)

output:

€4.44
€3.32
€3.93
€3.78
€4.06

Edit. I find WebElement list using a CSS selector:

price = browser.find_elements(by=By.CSS_SELECTOR, value="p.sc-gKPRtg.sc-cTVMo.gFSBHP.dJSocd")

This element list have 5 prices:

€4.44
€3.32
€3.93
€3.78
€4.06

I want to calculate average prices but I can't because this is WebElement List. I tried to extract this number without € by decimals:

price = browser.find_elements(by=By.CSS_SELECTOR, value="p.sc-gKPRtg.sc-cTVMo.gFSBHP.dJSocd")
for i in price:
    value_price = i.text
    value = Decimal(sub(r'[^\d.]', '', value_price))
    print(value)

Output:

4.44
3.32
3.93
3.78
4.06

And now I want to calculate average this numbers:

price = browser.find_elements(by=By.CSS_SELECTOR, value="p.sc-gKPRtg.sc-cTVMo.gFSBHP.dJSocd")
for i in price:
    value_price = i.text
    value = Decimal(sub(r'[^\d.]', '', value_price))
    print(value)
avg = sum(value)/len(value)
print(avg)

Output:

Traceback (most recent call last):
  File "C:\Users\sokal\PycharmProjects\pythonProject1\login_sorare.py", line 56, in <module>
    avg = sum(value)/len(value)
          ^^^^^^^^^^
TypeError: 'decimal.Decimal' object is not iterable

I'm not sure what's wrong because I can't use sum()/len().


Solution

  • sum() and len() are expecting a list but you are passing in just one value. That's why you are getting the object is not iterable error. There are a number of ways you can do this. One way is to take your existing code, add each .text value to an array, and then use sum() and len() to calculate the average.

    price_elements = browser.find_elements(by=By.CSS_SELECTOR, value="p.sc-gKPRtg.sc-cTVMo.gFSBHP.dJSocd")
    text_prices = [price_element.text for price_element in price_elements]
    prices = [float(text_price.replace('€', '')) for text_price in text_prices]
    average = sum(prices)/len(prices)
    print(average)
    

    ...and it prints

    3.9059999999999997