簡體   English   中英

將圖像從 RSS 提要保存到 Django 圖像字段

[英]Save Image from RSS Feed to Django Image Field

我有一個這樣的模型:

#models.py
class Post(models.Model):
    cover = models.ImageField(upload_to="news/", blank=True, max_length=255)

然后,我使用 BeautifulSoup4 從 RSS 提要中提取圖像 url:

#views.py
def pull_feeds(request, pk):
    source = Autoblogging.objects.get(pk=pk)
    url = requests.get(source.url)
    soup = BeautifulSoup(url.content, "html.parser")

    cover = soup.find('media:content')['url']
    Post.objects.create(cover=cover)

內容提要是這樣的

<media:content url="https://travelcommunication.net/wp-content/uploads/2021/10/Raffles-Hotels-Bring-Legendary-Hospitality-Experience-to-Romantic-Udaipur-TRAVELINDEX-TOP25HOTELS-500x300.jpg" width="500" height="300" medium="image" type="image/jpeg"/>

但它只保存 url,不保存圖像文件。 如何將實際圖像文件而不是 url 保存到該圖像?

您可以為圖像發送另一個GET請求並將響應寫入文件:

...
image = requests.get(cover)
with open("image.png", "wb") as f:
    f.write(image.content)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM