# model.py
from django.db import models
# Create your models here.
class Weather(models.Model):
Temperature = models.CharField(max_length=20)
Humidity = models.CharField(max_length=20)
Check_Time = models.CharField(max_length=20)
def __str__(self):
return self.name
# views.py
from django.shortcuts import render
from django.http import HttpResponse
import requests
from bs4 import BeautifulSoup
import time
from .models import Weather
# Create your views here.
def index(request):
req = requests.get('https://search.naver.com/search.naver?sm=tab_hty.top&where=nexearch&query=%EC%84%B1%EB%82%A8%EC%8B%9C+%EC%88%98%EC%A0%95%EA%B5%AC+%EC%8B%A0%ED%9D%A5%EB%8F%99+%EB%82%A0%EC%94%A8&oquery=%EC%84%B1%EB%82%A8%EC%8B%9C+%EC%88%98%EC%A0%95%EA%B5%AC+%EB%82%A0%EC%94%A8&tqi=UC6hpdprvhGssb2o%2B3Vssssssrl-217403')
html = req.text
weather = BeautifulSoup(html, 'html.parser')
bs1 = weather.find('div' , class_ = 'main_info')
bs2 = bs1.find('div' , class_ = 'info_data')
bs3 = bs2.find('p' , class_ = 'info_temperature')
bs4 = bs3.find('span' , class_ = 'todaytemp')
temp = bs4.text
bs1 = weather.find('div' , class_ = 'info_list humidity _tabContent')
bs2 = bs1.find('ul' , class_ = 'list_area')
bs3 = bs2.find('li' , class_ = 'on now')
bs4 = bs3.find('dd' , class_ = 'weather_item _dotWrapper')
bs5 = bs4.find('span')
humi = bs5.text
a = time.strftime('%Y-%m-%d %H:%M', time.localtime(time.time()))
Weather = {'Temperature':temp, 'Humidity':humi, 'time':a}
print("Temperature: %s°C & Humidity: %s%%" %(temp, humi))
# b = Weather(Temperature = temp, Humidity = humi, Check_Time = a)
# b.create()
# dic = {Weather.Temperature : temp, Weather.Humidity : humi, Weather.Check_Time : a}
# dic.save()
# q = Weather(Temperature=temp, Humidity=humi, Check_Time=a)
# q.save()
return render(request, 'Weather_data/index.html')
def update(request):
return HttpResponse('Update Page :)')
크롤링한 데이터를 홈페이지 접속시에 DB로 바로 저장되게 하고싶은데
DB저장 부분에서 자꾸 오류가 나서 질문드립니다.
# b = Weather(Temperature = temp, Humidity = humi, Check_Time = a)
# b.create()
'dict' object is not callable 에러 나오구요
# dic = {Weather.Temperature : temp, Weather.Humidity : humi, Weather.Check_Time : a}
# dic.save()
'dict' object has no attribute 'Temperature' 에러 나옵니다.
#q = Weather(Temperature=temp, Humidity=humi, Check_Time=a)
#q.save()
'dict' object is not callable 에러가 나오는데
어떻게 해야할까요
https://docs.djangoproject.com/en/3.0/topics/db/queries/#creating-objects
이 페이지 참고하였습니다