How to print only the texts using Beautifulsoup in Python?

Viewed 57

I want to print only the texts from here.

Here my HTML.Purser Code

import requests                                                  
from bs4 import BeautifulSoup                                    
                                                             
page = requests.get('https://www.vocabulary.com/dictionary/abet')
soup = BeautifulSoup(page.content, 'html.parser')                    
synonyms2 = soup.find_all(class_='short')                            
print(synonyms2[0])                                              
print(synonyms2[0].find(class_='short').get_text())   

Output

<p class="short">To <i>abet</i> is to help someone do something, usually something wrong. If 
you were the lookout while your older sister swiped cookies from the cookie jar, you 
<i>abetted</i> her mischief.</p>

Traceback (most recent call last):
File "/home/hudacse6/WebScrape/webscrape.py", line 8, in <module>
print(synonyms2[0].find(class_='short').get_text())
AttributeError: 'NoneType' object has no attribute 'get_text'

In my output i,m successfully print the class values associate with html tags but when i try to call only the texts using this line

print(synonyms2[0].find(class_='short').get_text())

it will me this error

 Traceback (most recent call last):
 File "/home/hudacse6/WebScrape/webscrape.py", line 8, in <module>
 print(synonyms2[0].find(class_='short').get_text())
 AttributeError: 'NoneType' object has no attribute 'get_text'. 

How to avoid this error and only print the texts.

1 Answers

You are getting the error because synonyms2[0].find(class_='short') returns None.

Use this instead:

Code

import requests                                                  
from bs4 import BeautifulSoup                                    

page = requests.get('https://www.vocabulary.com/dictionary/abet')
soup = BeautifulSoup(page.content, 'html.parser')                    
synonyms2 = soup.find_all(class_='short')                                                                        
print(synonyms2[0].get_text())

Output

To abet is to help someone do something, usually something wrong. If you were the lookout while your older sister swiped cookies from the cookie jar, you abetted her mischief.
Related