Как печатать только тексты с помощью Beautifulsoup в Python? - PullRequest
1 голос
/ 30 марта 2020

Я хочу напечатать только тексты отсюда.

Здесь мой 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())   

Вывод

<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/WebScrap/webscrap.py", line 8, in <module>
print(synonyms2[0].find(class_='short').get_text())
AttributeError: 'NoneType' object has no attribute 'get_text'

В моем выводе i, m успешно распечатывает значения класса, связанные с тегами html но когда я пытаюсь вызвать только тексты, использующие эту строку

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

, я получу эту ошибку

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

Как избежать этой ошибки и печатать только тексты.

1 Ответ

3 голосов
/ 30 марта 2020

Вы получаете ошибку, потому что synonyms2[0].find(class_='short') возвращает None.

Используйте это вместо:

Код

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())

Выход

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.
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...