【发布时间】:2021-06-04 04:46:32
【问题描述】:
我尝试使用 BeautifulSoup 从 class、id 等中清除 html,然后保存它们。
清除 html 工作正常,但是当我尝试保存时,我得到:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/local/lib/python3.7/site-packages/django/db/models/base.py", line 754, in save
force_update=force_update, update_fields=update_fields)
File "/usr/local/lib/python3.7/site-packages/django/db/models/base.py", line 792, in save_base
force_update, using, update_fields,
File "/usr/local/lib/python3.7/site-packages/django/db/models/base.py", line 873, in _save_table
forced_update)
File "/usr/local/lib/python3.7/site-packages/django/db/models/base.py", line 926, in _do_update
return filtered._update(values) > 0
File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 799, in _update
query.add_update_fields(values)
File "/usr/local/lib/python3.7/site-packages/django/db/models/sql/subqueries.py", line 108, in add_update_fields
val = val.resolve_expression(self, allow_joins=False, for_save=True)
TypeError: 'NoneType' object is not callable
我的代码:
@shared_task
def clean_article_html(article_id):
try:
article = Article.objects.get(id=article_id)
except ObjectDoesNotExist:
pass
else:
html = BeautifulSoup(article.body, 'html.parser')
for tag in html():
for attribute in ['class', 'id', 'name', 'style']:
del tag[attribute]
article.text = html
article.save()
也许有人知道这段代码有什么问题。
解决方案:(感谢 AbdulAzizBarkat)
article.text = str(html)
article.save()
【问题讨论】:
-
模型可能有问题。你介意用你的模型类更新你的问题吗?
-
article对象可能是None,您的代码可能在exception块中,但您已经pass编辑了它,因此您可以尝试检查exception -
for tag in html()但article.text = html。是否缺少()来调用函数? -
试试
article.text = str(html),如果还是不行,请将full错误回溯添加到问题中。 -
@AbdulAzizBarkat 您的解决方案工作!谢谢!
标签: django django-models beautifulsoup