使用scrapy爬取dota2贴吧数据并进行分析
一直好奇贴吧里的小伙伴们在过去的时间里说的最多的词是什么,那我们就来抓取分析一下贴吧发文的标题内容,并提取分析一下,看看吧友们在说些什么。
首先我们使用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贴吧数据并进行分析的更多相关文章
- Scrapy爬取到的中文数据乱码问题处理
Scrapy爬取到中文数据默认是 Unicode编码的,于是显示是这样的: "country": ["\u56fd\u4ea7\u6c7d\u8f66\u6807\u5f ...
- scrapy爬取booking酒店评论数据
# scrapy爬取酒店评论数据 -- 代码 here:github地址:https://github.com/760730895/scrapy_Booking-- 采用scrapy爬取酒店评论数据 ...
- 使用scrapy爬取网站的商品数据
目标是爬取网站http://www.muyingzhijia.com/上全部的商品数据信息,包括商品的一级类别,二级类别,商品title,品牌,价格. 搜索了一下,python的scrapy是一个不错 ...
- scrapy爬取伯乐在线文章数据
创建项目 切换到ArticleSpider目录下创建爬虫文件 设置settings.py爬虫协议为False 编写启动爬虫文件main.py
- Scrapy实战篇(八)之Scrapy对接selenium爬取京东商城商品数据
本篇目标:我们以爬取京东商城商品数据为例,展示Scrapy框架对接selenium爬取京东商城商品数据. 背景: 京东商城页面为js动态加载页面,直接使用request请求,无法得到我们想要的商品数据 ...
- 用scrapy爬取京东的数据
本文目的是使用scrapy爬取京东上所有的手机数据,并将数据保存到MongoDB中. 一.项目介绍 主要目标 1.使用scrapy爬取京东上所有的手机数据 2.将爬取的数据存储到MongoDB 环境 ...
- 如何提升scrapy爬取数据的效率
在配置文件中修改相关参数: 增加并发 默认的scrapy开启的并发线程为32个,可以适当的进行增加,再配置文件中修改CONCURRENT_REQUESTS = 100值为100,并发设置成了为100. ...
- 教你分分钟学会用python爬虫框架Scrapy爬取心目中的女神
本博文将带领你从入门到精通爬虫框架Scrapy,最终具备爬取任何网页的数据的能力.本文以校花网为例进行爬取,校花网:http://www.xiaohuar.com/,让你体验爬取校花的成就感. Scr ...
- Scrapy爬取美女图片 (原创)
有半个月没有更新了,最近确实有点忙.先是华为的比赛,接着实验室又有项目,然后又学习了一些新的知识,所以没有更新文章.为了表达我的歉意,我给大家来一波福利... 今天咱们说的是爬虫框架.之前我使用pyt ...
随机推荐
- bzoj2431
题意:求有多少个逆序对为k的排列 题解:\(dp[i][j]\)表示1~i的排列中有j个逆序对的方案数,转移就是把i放在1~i-1的排列中的第几位,\(dp[i][j]=\sum_{x=0}^{min ...
- HDU-6395-矩阵快速幂
Sequence Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 262144/262144 K (Java/Others)Total ...
- xlrd 安装步骤
官网 https://pypi.python.org/pypi/xlrd 下载 解压 执行python setup.py install进行安装 --------------------------- ...
- UI基础五:简单的OP组件POPUP搜索帮助
需求:给一个配置表,需要根据配置表来弹出选择框,并将选择的数据添加到SALES ORDER的项目 BSP_WD_CMPWB 新建组件:ZHSI_JPMPG 新建视图,适用VALUE NODE 参考表Z ...
- js向一个数组中插入元素的几个方法-性能比较
向一个数组中插入元素是平时很常见的一件事情.你可以使用push在数组尾部插入元素,可以用unshift在数组头部插入元素,也可以用splice在数组中间插入元素. 但是这些已知的方法,并不意味着没有更 ...
- python, 在信用评级中,计算KS statistic值
# -*- coding: utf-8 -*- import pandas as pd from sklearn.grid_search import GridSearchCV from sklear ...
- 2.Liunx 系统设置
1.基本命令:clear 2.环境变量: alias .export 大纲 系统管理命令 1.用户管理:adduser .passwd. userdel 2.用户组管理:groupadd.groupd ...
- 使用AJAX报406错误
使用AJAX报406错误,基本有一下两种情况: (1)90%的可能是没有添加jackson包: (2)10%的可能是请求的url后缀是*.html 在springmvc里面,如果请求的是*.html, ...
- tls 流量画像——直接使用图像处理的思路探索,待进一步观察
代码,示意了一个tls的数据内容: import numpy as np import matplotlib.pyplot as pyplot # !!! If on the server, use ...
- linux下sed命令详解
sed:Stream Editor文本流编辑,sed是一个“非交互式的”面向字符流的编辑器.能同时处理多个文件多行的内容,可以不对原文件改动,把整个文件输入到屏幕,可以把只匹配到模式的内容输入到屏幕上 ...