如何解决所有数据都填充到一行中
我是刮刀的初学者。我已经抓取了一些数据。这里有两个问题:所有数据都填充到一行中,并且每次刷新页面时,都将数据保存到数据库中。
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()
解决方法
您确实只在创建一个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
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。