最没有灵魂的爬虫——Selenium 游戏信息爬取与分析
准备工作
IDE选取
python本身自带的IDLE,也可以用一些编辑器,我个人使用的是pycharm,也可以使用一些其他的IDE。IDE的安装与配置很多,就不在这儿细说了。
selenium安装
Python装selenium很简单,直接在控制台执行pip就可以
pip install selenium
pycharm上的安装selenium
1.找到file,settings
2.找到对应的位置,点击绿色的“+”添加
3.在搜索栏输入selenium,就能找到对应的包
4.左下角安装,等待完成就好
ChromeDriver安装与配置
我在使用selenium的时候安装的Chromedriver,所以暂时只讲解Chromedriver的安装和配置
关于chromedriver与chrome版本映射表
转载:selenium之 chromedriver与chrome版本映射表
该文章下还有Chromedriver下载地址,我就不在这个页面贴上了(并不是因为懒 )
chromedriver的安装配置
下载好的chromedriver放到
C:\Program Files (x86)\Google\Chrome\Application
这个根据具体情况,放到你谷歌浏览器的Application文件夹中即可
还需要用到的其他python库
-
xlrd、xlwt
xlrd是读取Excel文件的库,xlwt是写入Excel文件的库,用Excel文件读取是为了数据分析对比(Excel的功能还是很强的)。当然也可以使用数据库来储存想要的信息 -
re
正则表达式 -
matplotlib
用python来画图(高逼格) -
collections
当前只会用到Counter,数据统计
数据爬取
接下来就是正式环节了,怎样用selenium从相应的网页中获取数据?
杉果游戏的数据获取
目标网址:https://www.sonkwo.com/store/search
先讲最开始的设置,url_base是请求的第一页,sortList和orderList是对网页的解析,当你点击该网页的这些栏时:
网页的链接会发生改变:
我们在请求数据的时候,就是通过改变网页地址栏中“?”后面所请求的数据,来获得不同的结果。
opt是对webdriver的设置,这里是设置webdriver无窗口,你可以注释opt.set_headless(),看看不同的效果。
allGameInfo就是我们python爬取数据后,数据暂时储存的位置,之后再写入excel表格中。
from selenium import webdriver
import xlwt
import re
#这是目标网址的第一页
url_base = "https://www.sonkwo.com/store/search?" \
"sort=wishes_count&order=desc&page=1"
url = 'https://www.sonkwo.com/store/search?'
sortList = ['released_at','score','wishes_count','price']
orderList = ['desc','asc']
page = ""
opt = webdriver.ChromeOptions()
opt.set_headless()
allGameInfo = []
#设置excel的表
f = xlwt.Workbook(encoding='utf-8',style_compression=0)
sheet = f.add_sheet('gameInfo', cell_overwrite_ok=True)
这两个函数是写入excel表格中的
#写Excel的表头
def writeExcelTitle():
row0 = ['游戏中文名字','游戏英文名','游戏类型','开发商','发行商','发售日期','游戏语言','售价']
for i in range(0, len(row0)):
sheet.write(0, i, row0[i])
#重allGame中获取数据并写入Excel表格中
def writeExcel():
for i in range(1, len(allGameInfo)):
for j in range(0, len(allGameInfo[i])):
sheet.write(i, j, allGameInfo[i][j])
f.save(r'gameInfoofSonkwo_demo02.xls')
这是一个网页元素判断,如果当前元素不存在,则返回false,虽然每一页大同小异,但还是有一些细微的差距,有些class或者id属性名的标签栏在某个页面是不存在的。
def isElementExisted(element, css):
flag = False
try:
element.find_element_by_css_selector(css)
flag = True
except:
flag = False
return flag
将数据保存到allGame中,driver有很多元素定位的方法
转载:[python爬虫] Selenium常见元素定位方法和操作的学习介绍
有些找不到的方法可以百度一下(又开始懒了 )
def fillGameInfo(driver):
singleInfo = []
#中文名
if(isElementExisted(driver, '.typical-name-1')):
singleInfo.append(driver.find_element_by_class_name('typical-name-1').text)
else:
singleInfo.append('')
#英文名
if(isElementExisted(driver, '.typical-name-2')):
singleInfo.append(driver.find_element_by_class_name('typical-name-2').text)
else:
singleInfo.append('')
#游戏类型
if