0

Using Python and Selenium, I am struggling to get CSS properties quickly and easily based on matched text from a search.

In this instance, I want to search a webpage for all instances of $ occurences, then, from whatever element they're found in, get the font-weight for those instances.

I cannot seem to do this without it being a very long and slow process.

Using beautiful soup doesn't help, as that can find the elements, and give me the class name, but then the "computed" css value for the element may differ from what the class name gives me.

I can search the html source and find instances of the $ character, I can then get each match and put this into a find_elements method, the problem is this is very, very slow and resource intensive, particular if there are many (like 50 or more) instances of $ characters in the source.

Is there something simple I'm missing here? I've also tried Reg Ex search within XPATH, but apparently XPATH1.0 does not properly support this.

Any help is much appreciated.

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
  • You'll probably need to execute javascript to get the "computedStyle". This thread covers it pretty well methinks: https://stackoverflow.com/questions/2664045/how-to-get-an-html-elements-style-values-in-javascript – pcalkins Aug 19 '22 at 17:39
  • Thank you for this, i'll take a look into it. It looks like using selenium to execute some javascript is going to give me what I need. – Milinekticker1 Aug 19 '22 at 17:47

1 Answers1

0

To extract the any of the CSS properties you can use the value_of_css_property(property_name) method. A couple of examples:

  • To extract the background-color

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "css_locator_of_element"))).value_of_css_property("background-color"))
    
  • To extract the background-image

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "css_locator_of_element"))).value_of_css_property("background-image"))
    
  • To extract the style

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "css_locator_of_element"))).value_of_css_property("style"))
    

References

You can find a couple of relevant detailed discussions in:

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
  • Thanks, I am aware of how to get the CSS properties themselves, my issue is knowing which element to use. My string search matches the returned text and a string position, ideally from here I need to get the exact xpath of said element so i can use this as a direct xpath locator strategy. – Milinekticker1 Aug 20 '22 at 07:26