虽然我使用facebook_scraper库从facebook页面获取带有此代码的帖子。
from facebook_scraper import get_posts
for post in get_posts('ThaiPBSFan', pages = 50):
print(post['text'][:100])
它很少发布,然后出现这样的错误。
Traceback (most recent call last):
File ".\main.py", line 2, in <module>
for post in get_posts('ThaiPBSFan', pages = 50):
File "C:\Users\admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\facebook_scraper.py", line 75, in _get_posts
yield _extract_post(article)
File "C:\Users\admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\facebook_scraper.py", line 102, in _extract_post
text, post_text, shared_text = _extract_text(article)
File "C:\Users\admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\facebook_scraper.py", line 137, in _extract_text
nodes = article.find('p, header')
AttributeError: 'NoneType' object has no attribute 'find'
所以有什么问题,我该如何解决。
从回溯来看,似乎facebook_scraper
没有返回有效的帖子;这可能是因为在该页面上找不到其他帖子。
因此,您可以使用try/except
块来捕获此异常,即:
try:
for post in get_posts('ThaiPBSFan', pages=50):
print(post['text'][:100])
except AttributeError:
print("No more posts to get")
这并不理想,因为一旦没有更多帖子可以检索,您最好能够获得一个更具体的例外,但是这种情况应该适合您的情况。在try
子句的内部代码中要小心-如果AttributeError
在其他任何地方都被加注,您将错过它。