爬虫大作业

1.选一个自己感兴趣的主题(所有人不能雷同)。

2.用python 编写爬虫程序,从网络上爬取相关主题的数据。

3.对爬了的数据进行文本分析,生成词云。

4.对文本分析结果进行解释说明。

5.写一篇完整的博客,描述上述实现过程、遇到的问题及解决办法、数据分析思想及结论。

6.最后提交爬取的全部数据、爬虫及数据分析源代码。

 

1、开发环境  

    编程语言:Python3.6

     代码运行工具:pycham

  依赖库:Requests,BeautifulSoup,wordcloud,re,jieba等

2、开发软件已经第三方库的安装

         由于开发软件的安装流程网上都有比较详细的介绍,所以在这里只是给出参考网站,具体讲一下的是第三方库的安装

  Python3.6的安装教程参照(https://jingyan.baidu.com/article/e9fb46e1502c5a7520f76640.html)

          pycham的安装教程参照  (https://jingyan.baidu.com/article/90895e0f28a32064ec6b0bc7.html)

 

在windows上安装python依赖库非常简单,语法如下:pip install PackageName  PackageName指的是你安装的依赖包名称。

  例如安装requests依赖包可以这样安装:pip install requests

但是以上的安装依赖包的方法用于wordcloud依赖包的安装是不行的,软件会报错的。我上网找了一下解决的方法有两个比较可行的。

第一个是去https://www.lfd.uci.edu/~gohlke/pythonlibs/#wordcloud选择合适的版本下载whl文件,注意的是,cp指的是系统上安装的python版本,32或者64表示安装的python版本是32位或者64位的,而不是你电脑的操作系统多少位的

           下载完成后打开cmd运行,切换到指定目录运行,代码如下:

pip install wordcloud-1.4.1-cp36-cp36m-win32.whl
pip install wordcloud

  其中wordcloud-1.4.1-cp36-cp36m-win32.whl是你下载的whl文件的名字或者说是你下载的whl 的版本。

第二个是去网站下载一个vs2017可以解决这个问题,不过这个软件太大了有几个G,下载什么的太浪费时间,不过在第一种情况你还不能解决wordcloud不能安装的问题也可以使用第二种

参考网站https://jingyan.baidu.com/article/597a06433b992e312b524384.html

要注意的是你使用的依赖包一定要都下载了,不然使用不了,特别是生成词云是时候使用到的jieba依赖包

 

 

3、爬虫程序的编辑以及生成词云

   

爬取广州商学院校园网新闻

# coding: utf-8
import re
import requests
from bs4 import BeautifulSoup
from datetime import datetime



def getClickCount(r):
    s = re.findall('\_(.*).html', r)[0].split('/')[-1]
    res = requests.get('http://oa.gzcc.cn/api.php?op=count&id={}&modelid=80'.format(s))
    return int(res.text.split('.html')[-1].lstrip("('").rstrip("');"))


def getNewsDetail(newsUrl):  # 一篇新闻的全部内容
    resd = requests.get(newsUrl)
    resd.encoding = 'utf-8'
    soupd = BeautifulSoup(resd.text, 'html.parser')  # 打开新闻详情并解析

    news = {}
    news['title'] = soupd.select('.show-title')[0].text
    info = soupd.select('.show-info')[0].text
    news['dt'] = datetime.strptime(info.lstrip('发布时间:')[0:19], '%Y-%m-%d %H:%M:%S')
    if info.find('来源:') > 0:
        news['source'] = info[info.find('来源:'):].split()[0].lstrip('来源:')
    else:
        news['source'] = 'none'
    news['content'] = soupd.select('.show-content')[0].text.strip()
    news['click'] = getClickCount(newsUrl)
    news['newsUrl'] = newsUrl
    return (news)


def getListPage(pageUrl):  # 9. 取出一个新闻列表页的全部新闻 包装成函数def getListPage(pageUrl)
    res = requests.get(pageUrl)
    res.encoding = 'utf-8'
    soup = BeautifulSoup(res.text, 'html.parser')

    newslist = []
    for news in soup.select('li'):
        if len(news.select('.news-list-title')) > 0:
            newsUrl = news.select('a')[0].attrs['href']
            newslist.append(getNewsDetail(newsUrl))
    return (newslist)


def getPageN():
    res = requests.get('http://news.gzcc.cn/html/xiaoyuanxinwen/')
    res.encoding = 'utf-8'
    soup = BeautifulSoup(res.text, 'html.parser')
    pagenumber = int(soup.select('.a1')[0].text.rstrip('条'))
    page = pagenumber // 10 + 1
    return page


newstotal = []
firstPageUrl = 'http://news.gzcc.cn/html/xiaoyuanxinwen/'
newstotal.extend(getListPage(firstPageUrl))
n = getPageN()
# f = open('gzccnews.txt','a',encoding='utf-8')
for i in range(n, n + 1):
    listPageUrl = 'http://news.gzcc.cn/html/xiaoyuanxinwen/{}.html'.format(i)
    newstotal.extend(getListPage(listPageUrl))

for news in newstotal:
    print(news)

import pandas
df = pandas.DataFrame(newstotal)
df.to_excel('gzccnews.xlsx')

# fo = open('output.txt', "ab+")
# # 以二进制写入章节题目 需要转换为utf-8编码,否则会出现乱码
# fo.write(('\r' + + '\r\n').encode('UTF-8'))
# # 以二进制写入章节内容
# fo.write(().encode('UTF-8'))
# fo.close()

  选取想要生成词云图片(可以根据你自己的喜欢更换你的选择)

 

生成词云

#coding:utf-8
import matplotlib.pyplot as plt
from wordcloud import WordCloud,ImageColorGenerator,STOPWORDS
import jieba
import numpy as np
from PIL import Image

#读入背景图片
abel_mask = np.array(Image.open("gui.jpg"))

#读取要生成词云的文件
text_from_file_with_apath = open('output.txt',encoding='utf-8').read()

#通过jieba分词进行分词并通过空格分隔
wordlist_after_jieba = jieba.cut(text_from_file_with_apath, cut_all = True)
wl_space_split = " ".join(wordlist_after_jieba)
#my_wordcloud = WordCloud().generate(wl_space_split) 默认构造函数
my_wordcloud = WordCloud(
            background_color='white',    # 设置背景颜色
            mask = abel_mask,        # 设置背景图片
            max_words = 800,            # 设置最大现实的字数
            stopwords = {}.fromkeys(['学院', '广州','法律','教师','新生','会议','主持','书记','学生']),        # 设置停用词
            font_path = 'C:/Users/Windows/fonts/simkai.ttf',# 设置字体格式,如不设置显示不了中文
            max_font_size = 50,            # 设置字体最大值
            random_state = 30,            # 设置有多少种随机生成状态,即有多少种配色方案
                scale=.5
                ).generate(wl_space_split)

# 根据图片生成词云颜色
image_colors = ImageColorGenerator(abel_mask)

# 以下代码显示图片
plt.imshow(my_wordcloud)
plt.axis("off")
plt.show()

  生成词云后的图片

 

posted @ 2018-04-28 16:49  233覃伟业  阅读(879)  评论(0编辑  收藏  举报