# -*- coding: utf-8 -*-
"""
Created on Thu Aug 16 14:52:09 2018
@author: Shirley
"""
#好评链接:http://www.dianping.com/shop/2044996/review_all/p2?queryType=reviewGrade&queryVal=good
#差评链接:http://www.dianping.com/shop/2044996/review_all/p2?queryType=reviewGrade&queryVal=bad
import requests
from lxml import etree
import xlrd
import random
import time
data = []
def Comments(url):
headers = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.75 Safari/537.36',
'Cookie': '浏览器获取的cookie'
}
#url = 'http://www.dianping.com/shop/19110508/review_all?queryType=reviewGrade&queryVal=bad'
resp = requests.get(url,headers=headers)
#print (resp.content.decode('utf-8'))#查看爬取网页代码,代码中文内容用二进制表示,故print时要decode
comments = etree.HTML(resp.text,parser=etree.HTMLParser(encoding='utf-8'))
commentlong = comments.xpath('//div[@class="review-words Hide"]')#长评
commentshort = comments.xpath('//div[@class="review-words"]')#短评
for l in commentlong:
data.append(l.xpath('string(.)').replace("\t","").replace("\n","").replace(" ","").replace("收起评论","").encode('gbk','ignore').decode('gbk'))
#把不需要的字符清除,可以用split()去掉\xa0,\t,\n,但是句子会被拆分成一个列表,不方便后续使用
for s in commentshort:
data.append(s.xpath('string(.)').replace("\t","").replace("\n","").replace(" ","").encode('gbk','ignore').decode('gbk'))
def getComments():
path = 'D:/anaconda/shirleylearn/dazhongdianping/negkey.xlsx'#抓取关键字
excelfile = xlrd.open_workbook(path)
keys = excelfile.sheet_by_name('Sheet1')
n = keys.nrows
for i in range(0,n):
key = int(keys.row(i)[0].value)
for page in range(1,int(keys.row(i)[1].value)+1):
url = 'http://www.dianping.com/shop/%d/review_all/p%d?queryType=reviewGrade&queryVal=bad'%(key,page)#拼链接,修改bad,good即为差评和好评
#print(url)
Comments(url)
time.sleep(random.random())
if __name__ == "__main__":
getComments()
print (len(data))
with open('neg.txt','w') as f:#把评论放入txt,好评改为pos.txt
for k in data:
f.write(k)
Python——大众点评评论爬虫代码
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 想了解一下吃货身上都有些什么特质。可以抓取点评的会员数据进行分析。 一、URL分析 这个是全国的会员榜,TOP30...
- WechatSogou [1]– 微信公众号爬虫。 基于搜狗微信搜索的微信公众号爬虫接口,可以扩展成基于搜狗搜索的...