客户端持续运营是提高客户端体验和用户黏性的一项重要工作,用户在IOS appstore和Android菜市场上的评论是很有价值的信息,自动抓取很有意思。
使用Python开发一个自动抓取用户评论的工具,是一件饶有趣味的事。
鉴于很多移动开发团队都有这方面的需求,所以把我的经验和大家分享一下。
我的代码是在淘宝抓取ios评论的代码上改进的,在此特别感谢淘宝天蒙同学的支持。 Android的菜市场很多,评论质量比较高的有:360手机助手,腾讯应用宝,豌豆荚以及小米市场等。
以360手机助手为例,客户端软件详情页面的信息包括评分,下载次数,更新时间,版本号以及用户评论等。
用Python的urllib2库可以获取页面内容,而使用Python第三方库BeautifulSoup以及正则表达式库re可以轻松地解析出你想要的字段。例如以下代码就是解析页面中的版本号,其他字段可以使用类似方法解析。
[backcolor=rgb(248, 248, 248) !important]2 | soup = BeautifulSoup(urllib2.urlopen(DETAIL_URL_360).read()) |
3 | version_str = soup('div', {'class':'nstxt'})[0].getText() |
[backcolor=rgb(248, 248, 248) !important]4 | version = re.findall('(\d+.\d+.\d+.\d+)', version_str)[0] |
评论的解析稍微复杂一点,因为大部分菜市场都是用ajax获取评论内容的,评论的内容在单独的url中返回,此时可以使用抓包工具如IEInspector来分析评论的连接。评论的内容一般都是json格式的,用python的json库解析就行了。
[backcolor=rgb(248, 248, 248) !important]2 | data = json.loads(urllib2.urlopen(comment_url).read())['data'] |
3 | comments = data['messages'] |
[backcolor=rgb(248, 248, 248) !important]4 | for comment in comments: |
详情和评论都解析出来以后,我们需要把它保存下来,使用sqlite数据库最方便,数据库就是一个文件。而Python为sqlite的访问提供了很方便的sqlite3模块。 1 | con = sqlite3.connect(DB_NAME) |
[backcolor=rgb(248, 248, 248) !important]
[backcolor=rgb(248, 248, 248) !important]
5 | cur.execute("INSERT INTO android_comment VALUES(?,?)",(‘xxx’,’yyy’)) |
[backcolor=rgb(248, 248, 248) !important]6 | except sqlite3.Error, e: |
7 | print "Sqlite Error %s:" % e.args[0] |
为了防止重复插入,使用作者+内容的md5值做唯一性校验: 1 | hashlib.md5(username+content).hexdigest() |
评论保存以后,使用Python的smtplib将评论邮件发送给相关同学。 01 | def send_mail(to_list,subject,content): |
[backcolor=rgb(248, 248, 248) !important]02 | me='%s<%s@%s>'%(mail_user,mail_user,mail_postfix) |
03 | msg = MIMEText(content, 'html', 'utf-8') |
[backcolor=rgb(248, 248, 248) !important]04 | msg['Subject'] = subject |
[backcolor=rgb(248, 248, 248) !important]06 | msg['To'] = ";".join(to_list) |
[backcolor=rgb(248, 248, 248) !important]
09 | #s.ehlo_or_helo_if_needed() |
[backcolor=rgb(248, 248, 248) !important]10 | s.login(mail_user,mail_pass) |
11 | s.sendmail(me, to_list, msg.as_string()) |
[backcolor=rgb(248, 248, 248) !important]
Android其他菜市场评论抓取与这很类似。不再赘述。
IOS appstore的评论抓取稍复杂一点,需要抓取详情页,评论页和评级页。
拿支付宝客户端来为例:
详情页为:http://itunes.apple.com/cn/app/zhi-fu-bao/id333206289?mt=8
评论页:http://itunes.apple.com/WebObjects/MZStore.woa/wa/customerReviews?displayable-kind=11&id=333206289&appVersion=current&sort=4
评级页:https://itunes.apple.com/cn/rss/topfreeapplications/limit=20/genre=6015/xml
用你客户端的id替换对应的id,用你客户端所属的类别替换genre即可。获取评级url的地址为:http://itunes.apple.com/rss/generator。 这些完成以后,我们希望每天定时发送,由于我是把代码部署在windows机器上,所以使用了一个好用的定制定时任务的工具ssfree。 附件中是所有代码,目前抓取了IOS appstore,360手机助手,腾讯应用宝以及豌豆荚的评论。
欢迎大家优化代码和新增功能
|