【发布时间】:2021-12-27 23:28:01
【问题描述】:
我编写了一个解析新闻文章提要的函数。
def save_new_articles(feed, source_id, category_id):
channel_feed_title = feed.channel.title.title()
channel_feed_link = feed.channel.link
channel_feed_desc = feed.channel.description
official_source_id = source_id
post_category_id = category_id
for item in feed.entries:
parsed_summary = item.summary
soup = BeautifulSoup(parsed_summary, 'lxml')
images = soup.findAll('img')
for image in images:
image_url_link = (image['src'])
if image_url_link is not None:
image_link = image_url_link
else:
image_link = "https://www.publicdomainpictures.net/pictures/280000/velka/not-found-image-15383864787lu.jpg"
parsed_title = item.title
formatted = re.sub("<.*?>", "", parsed_title)
post_title = formatted
post_link = item.link
description = item.description
output_summary = re.sub("<.*?>", "", description)
title = item.title
capital = title.title()
tags = capital.split()
date_published = parser.parse(item.published)
if not Posts.objects.filter(guid=item.guid).exists():
post = Posts(
title = post_title,
link = post_link,
summary = output_summary,
image_url = image_link,
tags = tags,
pub_date = date_published,
guid = item.guid,
feed_title = channel_feed_title,
feed_link = channel_feed_link,
feed_description = channel_feed_desc,
source_id = official_source_id,
category_id = post_category_id
)
post.save()
else:
logger.info("Duplicate Post Detected! Skipping...")
但是在运行代码时我得到:
image_url = image_link,
UnboundLocalError: local variable 'image_link' referenced before assignment
我不明白错误来自哪里,因为我在上面的image for loop statement 中定义了image_link。我已经检查了类似的答案,但我似乎没有找到合适的答案。请帮我调试一下。
【问题讨论】:
-
如果没有图像,
for image in images循环将永远运行。 -
@WillemVanOnsem 那么,当某些提要有图像而其他提要没有图像时,处理实例的最佳方法是什么?因为这就是我想要在那里实现的目标。
标签: python django function compiler-errors runtime-error