通过分析html页面,发现评论以http://club.jd.com/review/xxxx-1-1-0.html 这种形式单独表现。
通过分析html可知,评论即(心得)的位置。
html代码:
<div class="comment-content">
<dl>
<dt>标 签:</dt>
<dd>
<span class="comm-tags" href="#none"><span>信号稳定</span></span>
<span class="comm-tags" href="#none"><span>通话质量好</span></span>
<span class="comm-tags" href="#none"><span>电池耐用</span></span>
</dd>
</dl>
<dl>
<dt>心 得:</dt>
<dd>京东的东西质量就是不错,服务也很好</dd>
</dl>
..........
jd.py
# -*- coding: utf-8 -*-
import re,urllib,urllib2,requests
from BeautifulSoup import BeautifulSoup
url="http://club.jd.com/review/1196262-1-1.html"
response = urllib2.urlopen(url).read()
response=response.decode("gbk").encode("utf-8")
soup=BeautifulSoup(response)
*#print soup
#beautifulsoup 使用正则,质对标签进行匹配
#找出的评论范围太大,不准确
#reg=r"<dd>([^<]+)</dd>"
#comment=re.compile(reg).findall(response)
#缩小范围<dl> <dt>心 得:</dt> <dd>评论</dd> </dl> 后面才是评论*
comment=soup.findAll('div', attrs={'class':'comment-content'})
for i in comment:
#soup2=soup.findAll('dl')
if('心 得:' in str(i)):
c=re.search('<dd>([^<]+)</dd>',str(i)).group(1)
print c
#评论是一层一层嵌套的,这里一层一层解析,筛选。可能效率不高。但能达到效果
当时遇到问题:
1.首先是没有找到单独显示评论的页面,在一般商品页面中解析评论貌似很困难,查看源代码时html里面没有评论的信息。这和淘宝一样(通过高人指点获知单独显示评论的页面,嘿嘿)
2**.解码问题** 一般页面都是使用“gbk”但我解析的页面是“utf-8”,奇怪的是还是要用一般情况下的编码形式“gbk”.也就是,写爬虫时先要通过“gbk”解码,再转换成“utf-8”:decode(“gbk”).encode(“utf-8”)
3.爬取评论时使用嵌套循环。先从html中抽取
也可直接从有”心 得:”
里,检索到 对里的评论。