我想将使用硒获得的数据存储到django提供的数据库中。
但是我不能。请告诉我如何解决。
下面的代码是我的代码。
我的项目名称为'ebookranking',应用名称为'index'
#kyobo.py
from bs4 import BeautifulSoup
from selenium import webdriver
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ebookranking.settings')
import django
django.setup()
from index.models import Book
def kyobo():
driver = webdriver.Chrome('C:\\Users\\insutance\\PycharmProjects\\chromedriver')
driver.get('http://m.kyobobook.co.kr/digital/ebook/bestList.ink?cate_code=1&class_code=&barcode=&barcodes=&cate_gubun=&orderClick=&listCateGubun=1&listSortType=1&listSortType2=0&listSortType3=0&listSortType4=0&need_login=N&type=&returnUrl=%2Fdigital%2Febook%2FbestList.ink&reviewLimit=0&refererUrl=&barcodes_temp=&gubun=&ser_product_yn=&groupSort=1&groupSort2=0&groupSort3=0&groupSort4=0')
driver.implicitly_wait(2)
html = driver.page_source
soup = BeautifulSoup(html, 'html.parser')
titles = []
for n in range(1,31):
title = soup.select_one('#list > li:nth-child('+ str(n) +') > div.detail > p.pubTitle > a')
titles.append(title.text)
driver.quit()
return titles
if __name__=='__main__':
datas = kyobo()
for t in datas:
Book(title=t).save()
下面的代码是我的模型代码。
#models.py
from django.db import models
# Create your models here.
class Book(models.Model):
title = models.CharField(max_length = 200)
price = models.CharField(max_length = 10)
def __str__(self):
return self.title
答案 0 :(得分:0)
您必须按照documentation致电django.setup()
设置DJANGO_SETTINGS_MODULE或调用configure()之后, 您需要调用django.setup()来加载设置并填充 Django的应用程序注册表。例如:
import django from django.conf import settings from myapp import myapp_defaults settings.configure(default_settings=myapp_defaults, DEBUG=True) django.setup() # Now this script or any imported module can use any part of Django it needs. from myapp import models