How to print elements (xpath) text on a different line in selenium?



The title may sound confusing but I’m trying to get the .text() from an Xpath all on separate readable lines. For example you don’t see a book that is written in one line.
I’ve tried using for loops and had the idea of splitting the text so every 10 words it will add a new line but I can’t seem to get it to work. However I am very new to python and I’m pretty sure using for loops works and .split() works but I just can’t figure it out.

text = driver.find_element_by_xpath('//*[@id="mw-content-text"]/div[1]/p[1]')
text = text.split()

for i in text:

Any help will be appreciated.


To get the list of words:

    text = driver.find_element_by_xpath('//*[@id="mw-content-text"]/div[1]/p[1]').text
    list_of_words = text.split() # split by spaces between words
    sentence = []
    for word in list_of_words:  
        if(len(sentence) == 10):
            print(" ".join(sentence))
    print(" ".join(sentence))
    print("Text is not found")

Answered By – Muhteva

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More