时间:2023-09-05 00:00:01 | 来源:网站运营
时间:2023-09-05 00:00:01 来源:网站运营
python Django网页开发实战(1):最近一直在学习Django网页开发的内容,今天用Django简单的做一个电影页面网页,初步结果见图,总共分为三个步骤,数据获取(爬虫)、网页界面设计(html)、网页开发(Django),下面就一步一步来详细的讲解。import requestsimport csvfrom lxml import etreeimport pymysqlimport jsonimport reclass ConnMysql(): def __init__(self): # 连接数据库 self.db = pymysql.connect(host='localhost', port=3306, database='douban',#数据库名称 user='root', password='******',#数据库密码 charset='utf8') self.cursor = self.db.cursor() self.cursor.execute("DROP TABLE IF EXISTS movie") sql = ''' create table movie ( name Char(255), cover CHAR (255), disc TEXT (2555), address char (255)); ''' self.cursor.execute(sql) print('连接成功') def insert(self,dict1): # 将数据添加到数据库中的movie表中 sql = "insert into movie (name,cover,disc,address) values(%s,%s,%s,%s)" data = [dict1['name'],dict1['cover'],dict1['disc'],dict1['address']] try: self.cursor.execute(sql,data) self.db.commit() # 提交操作 except: self.db.rollback()
1.2 爬取数据class Douban(): def __init__(self): self.headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:2.0.1) Gecko/20100101 Firefox/4.0.1',} self.num=1000#爬取1000个数据,够我们用啦 self.url = 'https://movie.douban.com/j/new_search_subjects?sort=U&range=0,10&tags=%E7%94%B5%E5%BD%B1&start={}' self.douban_movie() def douban_movie(self): for page in range(0,self.num,20): print('开始第%s页'%page) self.get_url=self.url.format(str(page)) self.r=requests.get(url=self.get_url, headers=self.headers) self.r.encoding='utf-8' self.json_text=json.loads(self.r.text) self.parse_text() def parse_text(self): for moive_list in self.json_text['data']: # print(type(moive_list)) self.moive_name=moive_list['title'] self.movie_url=moive_list['url'] self.movie_cover=moive_list['cover'] self.parse_content() self.item={ 'name':self.moive_name, 'cover':self.movie_cover, 'disc':self.disc, 'address':self.movie_url, } self.save_data() def parse_content(self): self.r_disc = requests.get(url=self.movie_url, headers=self.headers) tree = etree.HTML(self.r_disc.text) self.disc = tree.xpath('//div[@id="link-report"]/span/text()') # /H4/a/@href' self.disc=re.sub(r'[/]//n ( /,)//u3000/[/']','',str(self.disc)) def save_data(self): database.insert(self.item)if __name__ == '__main__': database = ConnMysql() movie = Douban()
1.3打开Navicat Premium,连接数据库,可以看到在总的数据库中有douban数据库,其下面有movie列表,打开之后可以发现爬取到的数据已经全部存入到数据库中了。<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title> <style> /*解决页面浮动后的塌陷问题*/ .clearfix{ zoom:1; } .clearfix:after{ content: ''; display: block; visibility: hidden; line-height: 0; clear:both; } body,div{ margin: 0 auto; } div{ border: 1px solid gray; width: 750px; text-align:center; } ul{ list-style-type: none; display: inline-block; } #header li{ float:left; margin-left: 10px; font-size: 16px; font-family: '微软雅黑'; color:#666666 } #header li:hover{ cursor:pointer; background: blue; color:white; } #content li{ float:left; display: inline; margin-right: 15px; text-align: center; height: 120px; width: 120px; overflow: hidden; padding-top:10px; padding-bottom: 5px; } #content h1{ font-size:14px; margin:0; } .tip{ display: block; font-size: 12px; } .h1,.tip{ width:110px; text-align: center; } #content ul{ margin:0; margin-left: 55px; padding:0; } </style></head><body> <div id="header" class="clearfix"> <ul class="'clearfix"> <li>首页</li> <li>电影</li> <li>电视剧</li> <li>动漫</li> <li>综艺</li> <li>音乐</li> <li>MV</li> <li>视频</li> <li>短片</li> <li>公开课</li> </ul> </div> <div id="content"> <ul class="clearfix"> {% for movie in movies %} <li> <a href="{{ movie.address }}"><img src="{{ movie.cover }}" width="80px" height="80px"/></a> <h1 class="h1">{{ movie.name }}</h1> <span class="tip"> {{ movie.disc }}</span> </li> {% endfor %} </ul> </div> <div> <a href="/movie/?num={{ pre_page_num }}">上一页</a> <a href="/movie/?num={{ next_page_num }}">下一页</a> </div></body></html>
3、Django网页开发from django.contrib import adminfrom django.urls import path, includeurlpatterns = [ path('admin/', admin.site.urls), path('movie/',include('movieshow.urls'))]
设置完主url之后,在app中urls中进行子url设置,没有这个py文件的,右键新建一个,命名为urlsfrom django.urls import pathfrom . import viewsurlpatterns = [ path('',views.index_view),]
接着进行数据库映射D:/pythonstudy/django/movie>python manage.py inspectdb>movieshow/models.py
映射完成之后,可以发现在models中有字段的一些信息class Movie(models.Model): name = models.CharField(max_length=255, blank=True, primary_key=True) cover = models.CharField(max_length=255, blank=True, null=True) disc = models.TextField(blank=True, null=True) address = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = False db_table = 'movie'
完成以上操作之后,就可以在views中进行相关网页的显示与操作了def page(num,size=20): num=int(num) #总记录数 total=Movie.objects.count() totalpage=int(math.ceil(total*1.0/size)) #是否越界 if num<1: num=1 if num>totalpage: num=totalpage #每页显示记录 movies=Movie.objects.all()[((num-1)*size):(num*size)] # print(movies) return movies,numdef index_view(request): #接收前端请求参数 num=request.GET.get('num',1) #处理分页 movies,n=page(num) print(movies) #查询所有数据 # movies=Movie.objects.all() #上一页 pre_page_num=n-1 next_page_num=n+1 return render(request,'index01.html',{'movies':movies,'pre_page_num':pre_page_num,'next_page_num':next_page_num}) # return None
关键词:实战