通过 爬取2345电影网的电影信息 ,通过电影的类型和评分分别生成相应的词云 进行数据分析

一、准备过程

首先打开2345电影网的热播电影区,网址是https://dianying.2345.com/list/------.html

在这里可以通过审查模式看到第一页的详细信息,而目的则是通过爬取热播页面的每个电影的评分 和 类型来分析最近影迷的观影需求

环境如下:

python3.6.2    PyCharm

Windows7  第三方库(jieba,wordcloud,bs4,Requests,re,wordcloud)

二、代码

1.用requests库和BeautifulSoup库,爬取电影网当前页面的每个电影的电影名、评分、简介、地区、年代、链接等,将获取电影详情的代码定义成一个函数 def getNewDetail(newsUrl):

importrequestsimportrefrom bs4 importBeautifulSoupfrom datetime importdatetimeimportpandas

new={}

defgetNewsDetail(newsUrl):

resd=requests.get(newsUrl)

resd.encoding= 'gb2312'soupd= BeautifulSoup(resd.text, 'html.parser')print(newsUrl)

news={}

news['title']=soupd.select('.tit')[0].select('h1')[0].text #标题

news['emSorce']=float(soupd.select('.tit')[0].select('.pTxt')[0].text.split('\ue60e')[0].rstrip('分')) #评分

#s=soupd.select('.li_4')[1].text.split()[1:]

#if(len(s)>0):

#str=''

#for i in s:

#str=str+i

#print(str)

#writeNewsDetail(str)

news['content:']=soupd.select('.sAll')[0].text.strip() #内容

s = soupd.select('.wholeTxt')[0].text

news['area'] = s[s.find('地区:'):s.find('语言:')].split()[1] #地区

news['tit']=soupd.select('.li_4')[3].text.strip().split()[1] #年代

if len(soupd.select('.li_4')[3].text)>0:

news['tit']=soupd.select('.li_4')[3].text.strip().split()[1]else:

news['tit']=='none'new[soupd.select('.tit')[0].select('h1')[0].text ]= news['emSorce']return news

2.取出一个电影列表页的全部电影 包装成函数def getListPage(pageUrl):

defgetListPage(pageUrl):

res=requests.get(pageUrl)

res.encoding= 'gb2312'soup= BeautifulSoup(res.text, 'html.parser')

newslist=[]for i in soup.select('.v_tb')[0].select('li'):if (len(i.select('a')) >0):

newsUrl= 'https:' + i.select('a')[0].attrs['href']

newslist.append(getNewsDetail(newsUrl))return newslist

3.获取总的页数,算出电影总页数包装成函数def getPageN():

defgetPageN():

res= requests.get('https://dianying.2345.com/list/-------.html')

res.encoding= 'gb2312'soup= BeautifulSoup(res.text, 'html.parser')

pagenumber=int(soup.select('.v_page')[0].text.split('...')[1].rstrip('>')[0:3])return pagenumber

4.获取全部电影的详情信息(爬取页面前5页,原因在下方)

newstotal=[]

pageUrl='https://dianying.2345.com/list/-------.html'newstotal.extend(getListPage(pageUrl))

n=getPageN()for i in range(2,4):

listPageUrl= 'https://dianying.2345.com/list/-------{}.html'.format(i)

newstotal.extend(getListPage(listPageUrl))

df=pandas.DataFrame(newstotal)

dfs=df.sort_index(by='emSorce',ascending=False)

dfsn=dfs[['title','emSorce']]

dfsn.to_excel('gzcc.xlsx',encoding='utf-8')

将爬取到所有信息通过pandas根据评分排序,然后只爬取'title'和'emScore'两列的信息,并保存至excel表中

将爬取到的电影类别通过构造方法writeNewsDetail(content)写入到文本gzccnews.txt中,通过jieba分词,结果存至jieduo.txt中

defwriteNewsDetail(content):

f=open('gzccnews.txt','a',encoding='utf-8')

f.write(content)

f.close()

importjieba

f=open('gzccnews.txt','r',encoding="UTF-8")

str1=f.read()

f.close()

str2=list(jieba.cut(str1))

countdict={}for i instr2:

countdict[i]=str2.count(i)

dictList=list(countdict.items())

dictList.sort(key= lambda x:x[1],reverse =True)

f= open("E:/jieduo.txt", "a")for i in range(30):

f.write('\n' + dictList[i][0] + " " + str(dictList[i][1]))

f.close()

三、生成词云

通过导入wordcloud的包,来生成词云

importwordcloudfrom PIL importImage,ImageSequenceimportnumpy as npimportmatplotlib.pyplot as pltfrom wordcloud import WordCloud,ImageColorGenerator

image= Image.open('./63f7756ec660349a67874cfae7fc8643.jpg')

graph=np.array(image)

font=r'C:\Windows\Fonts\simhei.TTF'wc= WordCloud(font_path=font,background_color='White',max_words=50,mask=graph)

wc.generate_from_frequencies(countdict)

image_color=ImageColorGenerator(graph)

plt.imshow(wc)

plt.axis("off")

plt.show()

选择的图片:

生成词云的结果:

1.通过评分生成:

2.通过类型生成:

四、遇到的问题及解决方案

1.在爬取电影信息的时候,爬取电影年代的时候,会因为当前列表中当前列爬到某一处时,列表中的值没有,会报index out of range,上网搜索并不是下标越界的原因,这时候就尝试对当前的空值进行判断,如下图

#news['tit']=soupd.select('.li_4')[3].text.strip().split()[1] #年代

#if len(soupd.select('.li_4')[3].text.strip().split())==1:

#news['tit']=soupd.select('.li_4')[3].text.strip().split()[1]

#else:

#news['tit']=='none'

在加了判断后,可以输出一部分,但是在爬取所有页的时候还是会报错,找不到相应的错误信息,只好爬取前面近期的几页进行分析,一共140多部电影信息

2.在导入wordcloud这个包的时候,会遇到很多问题

首先通过使用pip install wordcloud这个方法在全局进行包的下载,可是最后会报错误error: Microsoft Visual C++ 14.0 is required. Get it with “Microsoft Visual C++ Build Tools”: http://landinghub.visualstudio.com/visual-cpp-build-tools

这需要我们去下载VS2017中的工具包,但是网上说文件较大,所以放弃。

之后尝试去https://www.lfd.uci.edu/~gohlke/pythonlibs/#wordcloud下载whl文件,然后安装。

下载对应的python版本进行安装,如我的就下载wordcloud-1.4.1-cp36-cp36m-win32.whl,wordcloud-1.4.1-cp36-cp36m-win_amd64

两个文件都放到项目目录中,两种文件都尝试安装

通过cd到这个文件的目录中,通过pip install wordcloud-1.4.1-cp36-cp36m-win_amd64,进行导入

但是两个尝试后只有win32的能导入,64位的不支持,所以最后只能将下好的wordcloud放到项目lib中,在Pycharm中import wordcloud,最后成功

五、数据分析与结论

通过对词云的查看,可以看出最近一年的影迷对于电影类型为动作、喜剧、爱情、犯罪的题材的电影喜欢,而对恐怖、历史、灾难等题材的电影选择很少,这说明观看电影选择的大多数是有关有趣一点的,而对于偏阴暗面的电影少选择,这样在拍摄电影时可以通过受众程度来拍摄。

在对最近热播的电影生成的词云来看,评分高的电影跟类型有很大的关系,所以影迷可以通过选择评分高的电影进行观看。

在这次作业中,我了解并实现如何爬取一个网站的有用信息,如何对爬取的信息分析并得到结论,但是对于大数据技术深度的技术并不了解,基础的知识还需要我不断加深巩固。

六、所有代码

#大数据大作业#爬取2345电影网中的电影评分最多的电影

importrequestsimportrefrom bs4 importBeautifulSoupfrom datetime importdatetimeimportpandas

new={}defwriteNewsDetail(content):

f=open('gzccnews.txt','a',encoding='utf-8')

f.write(content)

f.close()defgetNewsDetail(newsUrl):

resd=requests.get(newsUrl)

resd.encoding= 'gb2312'soupd= BeautifulSoup(resd.text, 'html.parser')#print(newsUrl)

news ={}

news['title']=soupd.select('.tit')[0].select('h1')[0].text #标题

news['emSorce']=float(soupd.select('.tit')[0].select('.pTxt')[0].text.split('\ue60e')[0].rstrip('分')) #评分

s=soupd.select('.li_4')[1].text.split()[1:]if(len(s)>0):

str=''

for i ins:

str=str+i#print(str)

writeNewsDetail(str)#news['content:']=soupd.select('.sAll')[0].text.strip() #内容

#s = soupd.select('.wholeTxt')[0].text

#news['area'] = s[s.find('地区:'):s.find('语言:')].split()[1] # 地区

#news['tit']=soupd.select('.li_4')[3].text.strip().split()[1] #年代

#if len(soupd.select('.li_4')[3].text)>0:

#news['tit']=soupd.select('.li_4')[3].text.strip().split()[1]

#else:

#news['tit']=='none'

new[soupd.select('.tit')[0].select('h1')[0].text ]= news['emSorce']returnnews#print(news)

defgetListPage(pageUrl):

res=requests.get(pageUrl)

res.encoding= 'gb2312'soup= BeautifulSoup(res.text, 'html.parser')

newslist=[]for i in soup.select('.v_tb')[0].select('li'):if (len(i.select('a')) >0):

newsUrl= 'https:' + i.select('a')[0].attrs['href']

newslist.append(getNewsDetail(newsUrl))returnnewslistdefgetPageN():

res= requests.get('https://dianying.2345.com/list/-------.html')

res.encoding= 'gb2312'soup= BeautifulSoup(res.text, 'html.parser')

pagenumber=int(soup.select('.v_page')[0].text.split('...')[1].rstrip('>')[0:3])returnpagenumber

newstotal=[]

pageUrl='https://dianying.2345.com/list/-------.html'newstotal.extend(getListPage(pageUrl))

n=getPageN()for i in range(2,4):

listPageUrl= 'https://dianying.2345.com/list/-------{}.html'.format(i)

getListPage(listPageUrl)#getListPage(pageUrl)#df=pandas.DataFrame(newstotal)#dfs=df.sort_index(by='emSorce',ascending=False)#dfsn=dfs[['title','emSorce']]#dfsn.to_excel('gzcc.xlsx',encoding='utf-8')

#import jieba#f=open('gzccnews.txt','r',encoding="UTF-8")#str1=f.read()#f.close()#str2=list(jieba.cut(str1))#countdict = {}#for i in str2:#countdict[i] = str2.count(i)#dictList = list(countdict.items())#dictList.sort(key = lambda x:x[1],reverse = True)#f = open("E:/jieduo.txt", "a")#for i in range(30):#f.write('\n' + dictList[i][0] + " " + str(dictList[i][1]))#f.close()

importwordcloudfrom PIL importImage,ImageSequenceimportnumpy as npimportmatplotlib.pyplot as pltfrom wordcloud importWordCloud,ImageColorGenerator

image= Image.open('./63f7756ec660349a67874cfae7fc8643.jpg')

graph=np.array(image)

font=r'C:\Windows\Fonts\simhei.TTF'wc= WordCloud(font_path=font,background_color='White',max_words=50,mask=graph)

wc.generate_from_frequencies(new)

image_color=ImageColorGenerator(graph)

plt.imshow(wc)

plt.axis("off")

plt.show()

python爬虫大作业任务书_爬虫大作业相关推荐

  1. python网页版百度_python,_爬虫 页面不存在_百度搜索,python - phpStudy

    爬虫 页面不存在_百度搜索 1.学写爬虫,遇到一个问题,加了values={"wd":"test","ie":"utf-8&quo ...

  2. python爬虫是数据挖掘吗_爬虫属于数据挖掘 python为什么叫爬虫

    数据挖掘和爬虫有区别吗? 数据挖掘和爬虫有很大的区别.数据挖掘过程应用于爬虫的可能性并不是特别大,但所占比例相对较大.但是使用爬虫,一般来说,爬虫都是爬到别人的网站上的,而且有些规则.因此,从数据挖掘 ...

  3. python爬虫实时更新数据_爬虫的增量式抓取和数据更新

    一些想法 页面爬的多了,量上去了之后,就会遇到其他的问题,其实不管做什么技术量大了都会有问题.一般情况下,我认为解决"大量"问题的思路有两个:一种是着力于优化系统的能力,让原本只能 ...

  4. 爬虫python和c语言区别_爬虫概述 - Python教程 - C语言网

    网络爬虫(又称为网页蜘蛛,网络机器人,更经常的称为网页追逐者),它按照一定的规则自动地抓取网络信息. 1. 产生背景 随着时代的进步,互联网上拥有大量的信息,但是我们该如何高效的获取这些信息成为了一个 ...

  5. python批量下载静态页面_爬虫实战之,爬取壁纸,批量下载

    一.前言 在开始写爬虫之前,我们先了解一下爬虫 首先,我们需要知道爬虫是什么,这里直接引用百度百科的定义 网络爬虫(又被称为网页蜘蛛,网络机器人,在FOAF社区中间,更经常的称为网页追逐者),是一种按 ...

  6. 《Python Spark 2.0 Hadoop机器学习与大数据实战_林大贵(著)》pdf

    <Python+Spark 2.0+Hadoop机器学习与大数据实战> 五星好评+强烈推荐的一本书,虽然内容可能没有很深入,但作者非常用心的把每一步操作详细的列出来并给出说明,让我们跟着做 ...

  7. 反爬虫兵法演绎04 _ 爬虫的首轮攻势:如何低调地拿到自己想要的数据?

    本资源由 Java学习者论坛 收集整理 04 | 爬虫的首轮攻势:如何低调地拿到自己想要的数据? 你好啊,我是DS Hunter.又见面了. 前面我和你聊了聊爬虫和反爬虫的历史,感觉这是一个内卷的死结 ...

  8. 工业制造中的大数据分析应用_工业大数据分析方案-美林数据

    认识工业大数据 什么是工业大数据? 我们先看看维基百科的说法:"工业大数据(Industrialbig data)是构成工业人工智能的重要元素,指由工业设备高速产生的大量数据,对应不同时间下 ...

  9. 观大数据有感_观大数据审计有感

    观大数据审计有感 拥抱大数据审计 从我做起 在审计系统集中整训的第四天, 我们聆听学习了一部分先进单位 关于大数据审计应用的经验交流, 审计是专业性很强的工作, 并且紧 跟时代不断更新,闭门造车不可取 ...

最新文章

  1. 学习一个 Linux 命令:shutdown 命令
  2. 操作系统开发系列—13.g.操作系统的系统调用 ●
  3. 存储世界瞬息万变 SSD掀行业浪潮
  4. Java Timestamp Memo
  5. [Prodinner项目]学习分享_第二部分_Entity到DB表的映射
  6. Python列表:list
  7. SpringCloud工作笔记049---nginx的安装及配置为简单的文件服务器
  8. 【南邮操作系统实验】页面置换算法(FIFO、LRU、OPT) Python 版
  9. 程序员如何淡定度过 2.14 情人节?
  10. Java面试的基础题20190301
  11. 博文视点新书样章下载
  12. typeof, offsetof, container_of宏
  13. Windows装机必备软件列表
  14. unionid openid微信php,微信的openID、unionID等总结
  15. 内点法外点法matlab代码,分享:惩罚函数法(内点法、外点法)求解约束优化问题最优值...
  16. C语言之结构体 共用体 枚举 typedef
  17. java笑话_[转]爆笑程序员的笑话集锦
  18. android 解压jar,解压和打包Jar - 海阔天空玩世不恭的个人空间 - OSCHINA - 中文开源技术交流社区...
  19. android mvp设计思想,android MVP 设计模式
  20. ssm人力资源考勤系统

热门文章

  1. 在Illustrator和手绘文章中创建矢量图形
  2. 少儿Python视频课程A级简介
  3. Axure的基本原件
  4. 【CSS】自定义平台文章封面图
  5. win+r常用组合键大全
  6. 烽火2640路由器命令行手册-14-桥接配置命令
  7. 2018天池大数据-印象盐城:数创未来大数据竞赛经验分享
  8. 内核RDMA模块(siw)代码分析
  9. Jhipster生成前端为Vue的项目引入Element-UI
  10. 前端面试复盘:vue技术面没有难倒我,hr面却是一把挂