-1

我是刮痧的初学者。我已经抓取了一些数据。这里有两个问题:所有数据都填充到一行中,每次刷新页面时,每次都将数据保存到数据库中。

import requests
from django.shortcuts import render, redirect
from bs4 import BeautifulSoup
from .models import Content

toi_r = requests.get("some web site")
toi_soup = BeautifulSoup(toi_r.content, 'html5lib')
toi_headings = toi_soup.findAll("h2", {"class": "entry-title format-icon"})[0:9]
toi_category = toi_soup.findAll("a", {"class": ""})[0:9]
toi_news = []
toi_cat =[]

for th in toi_headings:
    toi_news.append(th.text)

for tr in toi_category:
    toi_cat.append(tr.text)

#saving the files in database
n = Content()
n.title = toi_news
n.category = toi_cat
n.save()
4

1 回答 1

0

您确实只创建了一个 Django 对象。

您可以使用zip()将每个标题和类别配对,然后创建对象。(我还冒昧地将 for 循环缩短为简单的列表理解。)

toi_news = [th.text for th in toi_headings]
toi_cat = [tr.text for tr in toi_category]

for title, category in zip(toi_news, toi_cat):
    n = Content.objects.create(title=title, category=category)

至于“每次刷新页面时,每次都将数据保存到数据库中”——是的,好吧,视图代码是针对每个请求运行的。例如,您可以在创建一个标题之前检查是否存在Content具有相同标题的标题以避免这种情况。

于 2020-09-29T19:15:57.583 回答