【豆瓣影视数据分析】

一.获取数据源

def startUpMovie():count = 0#一共250部,每页25部,分十次爬取for i in range(0,10):for link, title, director, age, country, type, score, evaluationNum, note in getMovieList(str(25*i)):print('正在存储----{}'.format(""+title))# print(link, title, director, age, country, type, score, evaluationNum, note)cursor.execute("insert into movie(link, title, director, age, country, type, score, evaluationNum, note)"" values('{}', '{}','{}', '{}', '{}', '{}','{}', '{}', '{}')".format(link, (""+title), (""+director[6:]).strip("导演: ").strip().replace("'", r"\'"), (""+age).strip("\n").strip(),country, (""+type).strip("\n").strip().replace("'", r"\'"), score, evaluationNum[0:-3], note))getMovieContent(link, cursor.lastrowid)conn.commit()count += 1#每爬取两部电影,休眠7秒,以防止ip被禁!if count % 2 == 0:time.sleep(7)print("num:'{}'".format(count))#启动爬虫函数
startUpMovie()
  •  数据库配置
import pymysqlconn = pymysql.connect(host = 'localhost', #服务器ip地址port = 3306, #端口号db = 'movie',#数据库名字user = 'root', #数据库用户名passwd = '123456',#数据库密码charset = 'utf8mb4' #mysql中utf8不能存储4个字节的字符,此处与数据库中字符串编码类型都必须为utf8mb4
)cursor = conn.cursor()
cursor.execute('sql语句')
  •  python连接mysql数据库查询电影信息,并生成json数据,存储到本地文件里,以供前端js读取生成可视化图表:
  • typeNameList = ['剧情','喜剧','动作','爱情','科幻','悬疑','惊悚','恐怖','犯罪','同性','音乐','歌舞','传记','历史','战争','西部','奇幻','冒险','灾难','武侠','情色']
    def getMovieTypeJson():typeNumList = []for type in typeNameList:sql = r"select count(type) from movie where type like '%{}%'".format(type)dataM = getJsonData(sql)typeNumList.append(int(str(dataM).strip(r'(').strip(r',)')))return {'typeNameList' : typeNameList, 'typeNumList' : typeNumList}def writeTypeJsonFile(path):with open(path, 'w') as f:json.dump(getMovieTypeJson(), f)#执行写入操作
    writeTypeJsonFile(r'C:\Users\Administrator\Desktop\books\movieType.txt')
  • 对应前端代码
  • 
     
    
  • 生成图表结果
  • 按照type --> age --> country --> score --> movieLength --> title的顺序进行循环

  • 代码

  • def getMovieTreeJson():jsonFinal = '{"types": ['for type in typeNameList:sql = r"select distinct age from movie where type like '%{}%' order by age desc".format(type)ageList = getJsonData(sql)jsonFinal += '{{"name":"{}", "children":['.format(type)for age in getPureList(ageList):sql = r"select distinct country from movie where age = '{}' and type like '%{}%'".format(age, type)countryList = getJsonData(sql)countryArr = []jsonFinal += '{{"name":"{}", "children":['.format(age)for country in getPureList(countryList):if country.split(" ")[0] not in countryArr:countryArr.append(country.split(" ")[0])else:continuesql = r"select distinct score from movie where age = '{}' and type like '%{}%' and country like '{}%'" \r"order by score desc".format(age, type, country.split(" ")[0])scoreList = getJsonData(sql)jsonFinal += '{{"name":"{}", "children":['.format(country.split(" ")[0])for score in getPureList(scoreList):sql = r"select distinct movieLength from movie where age = '{}' and type like '%{}%' and country like '{}%'" \r"and score = '{}' order by score desc".format(age, type, country.split(" ")[0], score)movieLengthList = getJsonData(sql)jsonFinal += '{{"name":"分数{}", "children":['.format(score)for movieLength in getPureList(movieLengthList):jsonFinal += '{{"name":"时长{}", "children":['.format(movieLength)sql = r"select title, note from movie where age = '{}' and type like '%{}%' and country like '{}%'" \r"and score = '{}' and movieLength = '{}' order by score desc".format(age, type, country.split(" ")[0], score, movieLength)titleNoteList = getJsonData(sql)# print(age, type, country.split(" ")[0], score, movieLength, str(titleNoteList[0]).strip(","))for title, note in titleNoteList:jsonFinal += '{{"name":"{}", "value":"{}"}},'.format(title, note)# print(jsonFinal[:-1])jsonFinal = jsonFinal[:-1] + ']},'jsonFinal = jsonFinal[:-1] + ']},'jsonFinal = jsonFinal[:-1] + ']},'jsonFinal = jsonFinal[:-1] + ']},'jsonFinal = jsonFinal[:-1] + ']},'jsonFinal = jsonFinal[:-1] + ']},'return jsonFinal[:-1]def writeTreeJsonFile(path):with open(path, 'w') as f:json.dump(getMovieTreeJson(), f)writeTreeJsonFile(r'C:\Users\Administrator\Desktop\books\movieTreeJson.txt')
  • 
    
    
  • 查询年代得分
  • def getAgeScoreJson():ageScoreMap = {}ageScoreMap['ages'] = ['Growth']ageScoreMap['ageNames'] = []sql = r'select DISTINCT age from movie ORDER BY age desc'ageList = getPureList(getJsonData(sql))# print(ageList)for age in ageList:avgScoreList = []for type in typeNameList:sql = r"select avg(score) from movie where age = '{}' and type like '%{}%'".format(age, type)avgScore = str(getPureList(getJsonData(sql))).strip("['").strip("']")if avgScore == 'None':avgScore = 0avgScoreList.append(round(float(avgScore)))ageScoreMap[str(age)] = avgScoreListageScoreMap['ages'].append(str(age))# ageScoreMap['ageNames'].append('result.type' + str(age))ageScoreMap['names'] = typeNameListreturn ageScoreMapdef writeAgeScoreJsonFile(path):with open(path, 'w') as f:json.dump(getAgeScoreJson(), f)writeAgeScoreJsonFile(r'C:\Users\Administrator\Desktop\books\movieAgeScoreJson.txt')
  • 前端页面
  • 
    
    


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部