如何在Python中使用Beautifulsoup仅打印文本?

2024-07-02 13:06:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我只想打印这里的文本

这里是我的HTML.Purser代码

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

在我的输出中,我成功地打印了与html标记关联的类值,但是当我尝试使用这一行仅调用文本时

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

它会告诉我这个错误

 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'. 

如何避免此错误并仅打印文本


Tags: textfrom文本importgetpagefindrequests
1条回答
网友
1楼 · 发布于 2024-07-02 13:06:42

您得到错误是因为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.

相关问题 更多 >