爬虫大作业:
1.选一个自己感兴趣的主题(所有人不能雷同)。
2.用python 编写爬虫程序,从网络上爬取相关主题的数据。
3.对爬了的数据进行文本分析,生成词云。
4.对文本分析结果进行解释说明。
5.写一篇完整的博客,描述上述实现过程、遇到的问题及解决办法、数据分析思想及结论。
6.最后提交爬取的全部数据、爬虫及数据分析源代码。
爬虫大作业爬取的网站:http://sports.sina.com.cn/nba/。
爬虫源代码:
from urllib importrequestimportnumpy as npimportrequestsimportrefrom PIL importImagefrom bs4 importBeautifulSoupfrom datetime importdatetimefrom wordcloud importWordCloud, ImageColorGeneratorimportmatplotlib.pyplot as pltdefgetNewsDetail(Url):
resd=requests.get(Url)
resd.encoding= 'utf-8'soupd= BeautifulSoup(resd.text, 'html.parser') #打开新闻详情并解析
news ={}
news['76人总冠军'] = soupd.select('.main-title')[0].text.rstrip()print(news)return(news);
newslist=[]def getListPage(newsUrl): #9. 取出一个新闻列表页的全部新闻 包装成函数def getListPage(pageUrl)
res =requests.get(newsUrl)
res.encoding= 'utf-8'soup= BeautifulSoup(res.text, 'html.parser')for news in soup.select('.news-list-a ul li'):
Url= news.select('a')[0].attrs['href']#filmslist.append(getFilmsDetail(Url))
print(Url)
newslist.append(getNewsDetail(Url))return(newslist)#print(res.text)
newstotal=[]
firstPageUrl='http://sports.sina.com.cn/nba/'newstotal.extend(getListPage(firstPageUrl))
f= open('nba.txt', 'w', encoding='utf-8')
txtName= "nba.txt"f= open(txtName, "a+")
f.write(str(newstotal))
f.close()for news innewstotal:print(news)
f=open('nba.txt','r',encoding='GBK').read()
font=r'C:\Windows\Fonts\simkai.ttf'a=np.array(Image.open("enbide.jpg"))
wordcloud=WordCloud( background_color="white",font_path=font,width=1000,height=860,mask=a,margin=2).generate(f)
imagecolor=ImageColorGenerator(a)
plt.imshow(wordcloud)
plt.axis("off")
plt.show()
wordcloud.to_file('weibo.jpg')
python运行后的.txt文件:
生成词云:
总结:
在这次的python大作业中,遇到的做大的问题就是python的配置问题,wordcloud组件的导入出现的问题让我花费了许多的时间去解决。
1.用终端的命令下载wordcloud:
在cmd终端中,运用命令pip install wordcloud,进行安装wordcloud出现安装失败的问题。
2.然后百度后在这个网站上https://www.lfd.uci.edu/~gohlke/pythonlibs/#wordcloud下载whl文件,在终端上进行安装。
3.通过研究解决和同学们的帮忙,终于解决了wordcloud组件的安装问题。
这是安装完成后的:
代码文件类:
根据老师在课上的授课,我了解到了关于词频数据分析的有关的知识,对于词云上的一些问题通过自在百度上的学习和室友同学的帮忙也都顺利解决了!
主题爬取:
这次爬取的主题也是自己比较关注篮球比赛--NBA的赛事。这次的大作业是自己比较感兴趣的,在对数据的爬取时感觉很有趣。同时自己也受益颇多!