一直好奇贴吧里的小伙伴们在过去的时间里说的最多的词是什么,那我们就来抓取分析一下贴吧发文的标题内容,并提取分析一下,看看吧友们在说些什么。

首先我们使用scrapy对所有贴吧文章的标题进行抓取

scrapy startproject btspider

cd btspider

scrapy genspider -t basic btspiderx tieba.baidu.com

修改btspiderx内容

# -*- coding: utf-8 -*-
import scrapy from btspider.items import BtspiderItem class BTSpider(scrapy.Spider):
name = "btspider"
allowed_domains = ["baidu.com"]
start_urls = []
for x in xrange(91320):
if x == 0:
url = "https://tieba.baidu.com/f?kw=dota2&ie=utf-8"
else:
url = "https://tieba.baidu.com/f?kw=dota2&ie=utf-8&pn=" + str(x*50)
start_urls.append(url) def parse(self, response):
for sel in response.xpath('//div[@class="col2_right j_threadlist_li_right "]'):
item = BtspiderItem()
item['title'] = sel.xpath('div/div/a/text()').extract()
item['link'] = sel.xpath('div/div/a/@href').extract()
item['time'] = sel.xpath(
'div/div/span[@class="threadlist_reply_date pull_right j_reply_data"]/text()').extract()
yield item

修改items.py

# -*- coding: utf-8 -*-

# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html import scrapy class BtspiderItem(scrapy.Item):
title = scrapy.Field()
link = scrapy.Field()
time = scrapy.Field()

这里我们实际上保存的只是title标题内容

修改pipelines.py

# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
import codecs
import json class BtspiderPipeline(object):
def __init__(self):
self.file = codecs.open('info', 'w', encoding='utf-8')
def process_item(self, item, spider):
# line = json.dumps(dict(item)) + "\n"
titlex = dict(item)["title"]
if len(titlex) != 0:
title = titlex[0]
#linkx = dict(item)["link"]
#if len(linkx) != 0:
# link = 'http://tieba.baidu.com' + linkx[0]
#timex = dict(item)["time"]
#if len(timex) != 0:
# time = timex[0].strip()
line = title + '\n' #+ link + '\n' + time + '\n'
self.file.write(line)
return item
def spider_closed(self, spider):
self.file.close()

修改settings.py

BOT_NAME = 'btspider'
SPIDER_MODULES = ['btspider.spiders']
NEWSPIDER_MODULE = 'btspider.spiders'
ROBOTSTXT_OBEY = True
ITEM_PIPELINES = {
'btspider.pipelines.BtspiderPipeline': 300,
}

启动爬虫

scrapy crawl btspider

所有的标题内容会被保存为info文件

等到爬虫结束,我们来分析info文件的内容

github上有个示例,改改就能用

git clone https://github.com/FantasRu/WordCloud.git

修改main.py文件如下:

# coding: utf-8
from os import path
import numpy as np
# import matplotlib.pyplot as plt
# matplotlib.use('qt4agg')
from wordcloud import WordCloud, STOPWORDS
import jieba class WordCloud_CN:
'''
use package wordcloud and jieba
generating wordcloud for chinese character
''' def __init__(self, stopwords_file):
self.stopwords_file = stopwords_file
self.text_file = text_file @property
def get_stopwords(self):
self.stopwords = {}
f = open(self.stopwords_file, 'r')
line = f.readline().rstrip()
while line:
self.stopwords.setdefault(line, 0)
self.stopwords[line.decode('utf-8')] = 1
line = f.readline().rstrip()
f.close()
return self.stopwords @property
def seg_text(self):
with open(self.text_file) as f:
text = f.readlines()
text = r' '.join(text) seg_generator = jieba.cut(text)
self.seg_list = [
i for i in seg_generator if i not in self.get_stopwords]
self.seg_list = [i for i in self.seg_list if i != u' ']
self.seg_list = r' '.join(self.seg_list)
return self.seg_list def show(self):
# wordcloud = WordCloud(max_font_size=40, relative_scaling=.5)
wordcloud = WordCloud(font_path=u'./static/simheittf/simhei.ttf',
background_color="black", margin=5, width=1800, height=800) wordcloud = wordcloud.generate(self.seg_text) # plt.figure()
# plt.imshow(wordcloud)
# plt.axis("off")
# plt.show()
wordcloud.to_file("./demo/" + self.text_file.split('/')[-1] + '.jpg') if __name__ == '__main__':
stopwords_file = u'./static/stopwords.txt'
text_file = u'./demo/info' generater = WordCloud_CN(stopwords_file)
generater.show()

然后启动分析

python main.py

由于数据比较大,分析时间会比较长,可以拿到廉价的单核云主机上后台分析,等着那结果就好。

下边是我分析两个热门游戏贴吧的词云图片

使用scrapy爬取dota2贴吧数据并进行分析的更多相关文章

  1. Scrapy爬取到的中文数据乱码问题处理

    Scrapy爬取到中文数据默认是 Unicode编码的,于是显示是这样的: "country": ["\u56fd\u4ea7\u6c7d\u8f66\u6807\u5f ...

  2. scrapy爬取booking酒店评论数据

    # scrapy爬取酒店评论数据 -- 代码 here:github地址:https://github.com/760730895/scrapy_Booking--  采用scrapy爬取酒店评论数据 ...

  3. 使用scrapy爬取网站的商品数据

    目标是爬取网站http://www.muyingzhijia.com/上全部的商品数据信息,包括商品的一级类别,二级类别,商品title,品牌,价格. 搜索了一下,python的scrapy是一个不错 ...

  4. scrapy爬取伯乐在线文章数据

    创建项目 切换到ArticleSpider目录下创建爬虫文件 设置settings.py爬虫协议为False 编写启动爬虫文件main.py

  5. Scrapy实战篇(八)之Scrapy对接selenium爬取京东商城商品数据

    本篇目标:我们以爬取京东商城商品数据为例,展示Scrapy框架对接selenium爬取京东商城商品数据. 背景: 京东商城页面为js动态加载页面,直接使用request请求,无法得到我们想要的商品数据 ...

  6. 用scrapy爬取京东的数据

    本文目的是使用scrapy爬取京东上所有的手机数据,并将数据保存到MongoDB中. 一.项目介绍 主要目标 1.使用scrapy爬取京东上所有的手机数据 2.将爬取的数据存储到MongoDB 环境 ...

  7. 如何提升scrapy爬取数据的效率

    在配置文件中修改相关参数: 增加并发 默认的scrapy开启的并发线程为32个,可以适当的进行增加,再配置文件中修改CONCURRENT_REQUESTS = 100值为100,并发设置成了为100. ...

  8. 教你分分钟学会用python爬虫框架Scrapy爬取心目中的女神

    本博文将带领你从入门到精通爬虫框架Scrapy,最终具备爬取任何网页的数据的能力.本文以校花网为例进行爬取,校花网:http://www.xiaohuar.com/,让你体验爬取校花的成就感. Scr ...

  9. Scrapy爬取美女图片 (原创)

    有半个月没有更新了,最近确实有点忙.先是华为的比赛,接着实验室又有项目,然后又学习了一些新的知识,所以没有更新文章.为了表达我的歉意,我给大家来一波福利... 今天咱们说的是爬虫框架.之前我使用pyt ...

随机推荐

  1. K8S各知识点整理

    一.k8s组成部分 Master 1.   kube-apiserver 封装了核心对象的增删改查操作,以REST API接口方式提供给外部和内部组件调用.它维护的REST对象将持久化到Etcd中 2 ...

  2. python中for循环的底层实现机制 迭代

    在python中,存在2种循环方式:for循环和while循环. while循环的实现很简单, 其本质就是一个条件语句,自定义条件,当条件满足的时候,不断执行while代码块. 但是for循环,究竟是 ...

  3. win php安装 oracle11 g

    1.下载plsql和oracle11g plsql安装比较简单,就是普通的安装.oracle11 g不用安装, 下面我讲解一下win 64位的系统配置oracle: (1).首先我使用的是warpse ...

  4. ​ 用一个开发案例详解Oracle临时表

    ​ 用一个开发案例详解Oracle临时表 2016-11-14 bisal ITPUB  一.开发需求  最近有一个开发需求,大致需要先使用主表,或主表和几张子表关联查询出ID(主键)及一些主表字段 ...

  5. PAT 1019 General Palindromic Number

    1019 General Palindromic Number (20 分)   A number that will be the same when it is written forwards ...

  6. Leetcode 1021. 最佳观光组合

    1021. 最佳观光组合  显示英文描述 我的提交返回竞赛   用户通过次数91 用户尝试次数246 通过次数92 提交次数619 题目难度Medium 给定正整数数组 A,A[i] 表示第 i 个观 ...

  7. 时间序列八: 以NASA之名: 卡尔曼滤波器

    目录 以NASA之名: 卡尔曼滤波器 引言 荣耀骑士 卡尔曼滤波器* 参考文献: 以NASA之名: 卡尔曼滤波器 'That's one small step for man,one giant le ...

  8. 【LeetCode】Anagram

    Anagram 指由颠倒字母顺序而构成的单词. e.g. 给出 ["eat", "tea", "tan", "ate", ...

  9. 一、SQLite学习

    由于公司业务拓展,需要开发一个基于ASP.NET Core2.0+AdminLTE架构的后台管理系统,数据库选择方面,选择了使用SQLite轻便. SQLite:一个软件库,实现自给自足,无服务器,零 ...

  10. js中如何返回一个存放对象的数组?

    我这边需要返回后台数据的形式是这样的 {[ { ", }, { ", }, { ", }, { ", }, { ", } ]} 页面是通过循环去获取每 ...