【问题标题】:I want to insert data into MySQL database with Django我想用 Django 将数据插入 MySQL 数据库
【发布时间】:2022-01-02 21:13:06
【问题描述】:

我正在做网络抓取,我想将信息存储在数据库中。我在“设置”文件中与数据库连接,如下所示:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'dbname',
        'USER': 'root',
        'PASSWORD': 'password',
        'HOST': 'localhost',
        'PORT': 'port'
    }
}

网页抓取我把它放在另一个文件中,像这样:

from bs4 import BeautifulSoup
import requests

url = "https://www.somepage.com"
result = requests.get(url)
soup = BeautifulSoup(result.text, "html.parser")

find_by_class = soup.find('div', attrs={"class":"body"}).find_all('p')

我想将 find_by_class 中的内容存储在数据库中。

我还创建了模型。

from django.db import models

class SomeModel(models.Model):
    description = models.TextField(max_length=1000)

【问题讨论】:

  • 向我们展示您尝试将代码 sn-p 与模型连接起来的方法!到目前为止,我认为两者之间没有任何关系。
  • @KlausD。我试图在抓取文件中创建一个 from models import SomeModel ,然后尝试了这个 description = find_by_class 。但它当然没有用。

标签: python mysql django database beautifulsoup


【解决方案1】:

我假设您已经在数据库中完成了迁移(如果没有,则在项目的根文件夹中,运行python manage.py makemigrations,然后运行python manage.py migrate)。

现在你需要使用下面的sn-p:

from bs4 import BeautifulSoup
import requests
from .models import SomeModel

url = "https://www.somepage.com"
result = requests.get(url)
soup = BeautifulSoup(result.text, "html.parser")
find_by_class = soup.find('div', attrs={"class":"body"}).find_all('p') 
for each in find_by_class:
    SomeModel.objects.create(description=each.text)

【讨论】:

  • 是的,我进行了迁移并创建了 0001_initial 文件。
  • 这出现在输出中:“ModuleNotFoundError: No module named 'models'”
  • 包含报废代码和模型的文件应该在同一个 django app 文件夹中。否则从 someapp 导入模型,例如 from appname.models import SomeModel
  • 现在我得到这个:'ImportError:尝试相对导入,没有已知的父包'。尝试创建一个新项目进行验证,同样会发生。
  • 去掉'.'从模型中得到这个:ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
猜你喜欢
  • 1970-01-01
  • 2023-04-10
  • 2013-05-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-16
  • 1970-01-01
  • 2013-03-25
相关资源
最近更新 更多