我只想打印这里的文本
这里是我的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'.
如何避免此错误并仅打印文本
您得到错误是因为
synonyms2[0].find(class_='short')
返回None
改用这个:
代码
输出
相关问题 更多 >
编程相关推荐