【问题标题】:All the datas are populated into a single row所有数据都填充到一行中
【发布时间】:2021-01-15 10:43:56
【问题描述】:

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

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()

【问题讨论】:

    标签: python django web-scraping beautifulsoup django-request


    【解决方案1】:

    您确实只创建了一个 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 以避免这种情况。

    【讨论】:

    • 请详细说明
    • 当然,你可以简单地做if not Content.object.filter(title=title).exists():
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-21
    • 2016-01-08
    • 2016-10-06
    • 1970-01-01
    • 2019-03-23
    • 2021-06-06
    • 1970-01-01
    相关资源
    最近更新 更多