I would like to extract the text between ::before and ::after into a string. How can I use a for loop to extract all the text in selenium Python?
            Asked
            
        
        
            Active
            
        
            Viewed 1,834 times
        
    2 Answers
3
            The text i is in between the ::before and ::after pseudoelements. So to extract the text you can use either of the following Locator Strategies:
Using css_selector:
print(driver.find_element(By.CSS_SELECTOR, "div.kbkey.button.red").text)Using xpath:
print(driver.find_element(By.XPATH, "//div[@class='kbkey button red']").text)
Ideally you need to induce WebDriverWait for the visibility_of_element_located() and you can use either of the following Locator Strategies:
Using CSS-SELECTOR:
print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.kbkey.button.red"))).text)Using XPATH:
print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='kbkey button red']"))).text)Note : You have to add the following imports :
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC
You can find a relevant discussion in How to retrieve the text of a WebElement using Selenium - Python
References
Link to useful documentation:
- get_attribute() method gets the given attribute or property of the element.
 - text attribute returns the text of the element.
 - Difference between text and innerHTML using Selenium
 
        undetected Selenium
        
- 183,867
 - 41
 - 278
 - 352
 
1
            
            
        ::before and ::after are just a pseudo elements.
Here you can extract the text from the div element itself.
In case there are several divs with class kbkey button red you can do something like this:
buttons = driver.find_elements_by_css_selector("div.kbkey.button.red")
for button in buttons:
    print(button.text)
        Prophet
        
- 32,350
 - 22
 - 54
 - 79
 
- 
                    this totally worked for me. I saw the print statements in my use case showing the text in the 2nd of of 3 loops. Thanks! – rom Oct 05 '22 at 07:05
 - 
                    To add some context... It appears when ::before and ::after are present you should use .find_elements. The reason is this situation creates a 3 item array and the middle item is your text! So, to grab that, set up a variable prior to this point that gets the value if text is found. Also, I had to call .text in the for loop on the for-loop variable representing the selenium object. – rom Oct 05 '22 at 07:25
 - 
                    1@rom You are more than welcome! And thanks for the detailed explanations! – Prophet Oct 05 '22 at 17:06
 
