简体   繁体   English

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

[英]How to print only the texts using Beautifulsoup in Python?

I want to print only the texts from here.我只想打印这里的文本。

Here my HTML.Purser Code这是我的 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())   

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在我的输出中,我成功打印了与 html 标签关联的类值,但是当我尝试仅使用此行调用文本时

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.如何避免此错误并仅打印文本。

You are getting the error because synonyms2[0].find(class_='short') returns None .您收到错误是因为synonyms2[0].find(class_='short')返回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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM