# -*- coding: utf-8 -*-
# @author: Tele
# @Time : 2019/04/14 下午 3:48
# 多线程版
import time
import requests
import os
import json
from fake_useragent import UserAgent
from lxml import etree
import threading
from concurrent.futures import ThreadPoolExecutor, wait, as_completed class JDSplier:
executor = ThreadPoolExecutor(max_workers=6)
mutex = threading.Lock()
flag = True @staticmethod
def get_proxy():
return requests.get("http://127.0.0.1:5010/get/").content.decode() @staticmethod
def get_ua():
ua = UserAgent()
return ua.random def __init__(self, kw_list):
self.kw_list = kw_list
# 评论url
self.url_temp = "https://sclub.jd.com/comment/productPageComments.action?&productId={}&score=0&sortType=5&page={}&pageSize=10&isShadowSku=0&rid=0&fold=1"
self.headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36", }
self.proxies = {
"http": None
}
self.parent_dir = None
self.file_dir = None # ua,proxy
def check(self):
self.headers["User-Agent"] = JDSplier.get_ua()
proxy = "http://" + JDSplier.get_proxy()
self.proxies["http"] = proxy
print("ua:", self.headers["User-Agent"])
print("proxy:", self.proxies["http"]) # 评论
def parse_url(self, product_id, page):
url = self.url_temp.format(product_id, page)
response = requests.get(url, headers=self.headers, proxies=self.proxies, verify=False)
if response.status_code == 200:
print(url)
data = None
if len(response.content) < 0:
return
# 很奇葩
try:
data = json.loads(response.content.decode("gbk"))
except:
data = json.loads(response.content.decode())
finally:
# 评论
if not data:
return
comment_list = data["comments"]
if len(comment_list) > 0:
item_list = list()
for comment in comment_list:
item = dict()
# 商品名
item["referenceName"] = comment["referenceName"]
# 评论时间
item["creationTime"] = comment["creationTime"]
# 内容
item["content"] = comment["content"]
item_list.append(item) # 保存
with open(self.file_dir, "a", encoding="utf-8") as file:
file.write(json.dumps(item_list, ensure_ascii=False, indent=2))
file.write("\n")
time.sleep(5)
else:
JDSplier.flag = False
else:
print("请求失败!") # 提取id
def get_product_info(self):
url_temp = "https://search.jd.com/Search?keyword={}&enc=utf-8"
result_list = list()
for kw in self.kw_list:
url = url_temp.format(kw)
response = requests.get(url, headers=self.headers, proxies=self.proxies, verify=False)
if response.status_code == 200:
item_dict = dict()
id_list = list()
html_element = etree.HTML(response.content)
# 获得该关键词下第一页的商品id,前10个
id_list = html_element.xpath("//div[@id='J_goodsList']/ul/li[position()<11]/@data-sku")
item_dict["title"] = kw
item_dict["id_list"] = id_list
result_list.append(item_dict)
else:
pass
return result_list def get_comment(self, item_list):
if len(item_list) > 0:
for item in item_list:
id_list = item["id_list"]
item_title = item["title"]
if len(id_list) > 0:
# 检查目录
self.parent_dir = "f:/jd_comment/" + item_title + time.strftime("-%Y-%m-%d-%H-%M-%S",
time.localtime(time.time()))
if not os.path.exists(self.parent_dir):
os.makedirs(self.parent_dir)
task_list = list()
# 每个商品开启一个线程爬取评论
for product_id in id_list:
t = JDSplier.executor.submit(self.job, product_id)
time.sleep(10)
task_list.append(t)
for re in as_completed(task_list):
re.result(timeout=500)
# wait(task_list, timeout=500)
else:
print("---error,empty id list---")
else:
print("---error,empty item list---") def job(self, product_id):
self.check()
JDSplier.mutex.acquire()
page = 0
self.file_dir = self.parent_dir + "/" + str(product_id) + "_ratecontent.txt"
# 爬取评论
while JDSplier.flag:
self.parse_url(product_id, page)
page += 1
JDSplier.flag = True
JDSplier.mutex.release() def run(self):
# self.check()
item_list = self.get_product_info()
print(item_list)
self.get_comment(item_list)
JDSplier.executor.shutdown() def main():
# "华为p30pro", "华为mate20pro",
# "vivoz3""oppok1","荣耀8x", "小米9", "小米mix3", "三星s9", "iphonexr", "iphonexs"
kw_list = ["vivoz3"]
splider = JDSplier(kw_list)
splider.run() if __name__ == '__main__':
main()

ps:能多睡就多睡会,虽然很慢,但不会触发jd的安全系统,爬这种电商平台还是他们的活动日时比较好爬,那个时候为了应对超高的访问量,一般会暂时关闭反爬机制

毕设二:python 爬取京东的商品评论的更多相关文章

  1. Python 爬取淘宝商品数据挖掘分析实战

    Python 爬取淘宝商品数据挖掘分析实战 项目内容 本案例选择>> 商品类目:沙发: 数量:共100页  4400个商品: 筛选条件:天猫.销量从高到低.价格500元以上. 爬取淘宝商品 ...

  2. Scrapy实战篇(八)之Scrapy对接selenium爬取京东商城商品数据

    本篇目标:我们以爬取京东商城商品数据为例,展示Scrapy框架对接selenium爬取京东商城商品数据. 背景: 京东商城页面为js动态加载页面,直接使用request请求,无法得到我们想要的商品数据 ...

  3. JS+Selenium+excel追加写入,使用python成功爬取京东任何商品~

    之前一直是requests库做爬虫,这次尝试下使用selenium做爬虫,效率不高,但是却没有限制,文章是分别结合大牛的selenium爬虫以及excel追加写入操作而成,还有待优化,打算爬取更多信息 ...

  4. 使用Python 爬取 京东 ,淘宝。 商品详情页的数据。(避开了反爬虫机制)

    以下是爬取京东商品详情的Python3代码,以excel存放链接的方式批量爬取.excel如下 代码如下 from selenium import webdriver from lxml import ...

  5. python爬取京东评论

    一.分析 1.找到京东商品评论所在位置(记得点击商品评论,否则找不到productPageComments.action)  2.解析文件 打开后发现是json数据,但不是那么规范,所以需要去点前面的 ...

  6. 毕设之Python爬取天气数据及可视化分析

    写在前面的一些P话:(https://jq.qq.com/?_wv=1027&k=RFkfeU8j) 天气预报我们每天都会关注,我们可以根据未来的天气增减衣物.安排出行,每天的气温.风速风向. ...

  7. python 爬取天猫美的评论数据

    笔者最近迷上了数据挖掘和机器学习,要做数据分析首先得有数据才行.对于我等平民来说,最廉价的获取数据的方法,应该是用爬虫在网络上爬取数据了.本文记录一下笔者爬取天猫某商品的全过程,淘宝上面的店铺也是类似 ...

  8. python利用urllib实现的爬取京东网站商品图片的爬虫

    本例程使用urlib实现的,基于python2.7版本,采用beautifulsoup进行网页分析,没有第三方库的应该安装上之后才能运行,我用的IDE是pycharm,闲话少说,直接上代码! # -* ...

  9. 毕设一:python 爬取苏宁的商品评论

    毕设需要大量的商品评论,网上找的数据比较旧了,自己动手 代理池用的proxypool,github:https://github.com/jhao104/proxy_pool ua:fake_user ...

随机推荐

  1. 3. ZAB与Paxos算法的联系与区别。

    转自:https://blog.csdn.net/en_joker/article/details/78665809 ZAB协议并不是Paxos算法的一个典型实现,在讲解ZAB和Paxos之间的区别之 ...

  2. 100.dll调用

    在dll中声明 _declspec(dllexport) ; _declspec(dllexport)void go() { MessageBoxA(, ); } 调用dll HINSTANCE hl ...

  3. 微信支付v2开发(9) 标记客户投诉处理状态

    本文介绍微信支付中如何标记客户投诉的处理状态. 一.API Api 的 url 为: https://api.weixin.qq.com/payfeedback/update?access_token ...

  4. 11G、12C Data Guard Physical Standby Switchover转换参考手册

    Switchover转换   Step 1: switchover 切换先前检查 (1)确保主备两端log_archive_config和db_unique_name参数都已经正确设置. 需要注意的是 ...

  5. JS contcat() 连接数组 函数

    语法: arrayObject.concat(arrayX,arrayX,......,arrayX) 1.把元素添加到数组中 arr.concat(a,b,c);2.把数组连起来 arr.conca ...

  6. 【CS Round #48 (Div. 2 only)】Game of Chance

    [链接]h在这里写链接 [题意] 在这里写题意 [题解] 在这里写题解 [错的次数] 0 [反思] 在这了写反思 [代码] #include <bits/stdc++.h> using n ...

  7. Nginx 虚拟主机及正向代理设置

    添加虚拟主机 # vim /usr/local/nginx-1.9.0/conf/vhost/proxy.conf  server { resolver 8.8.8.8; listen ; locat ...

  8. SpringBoot错误信息总结(不定时更新)

    1." java.lang.IllegalStateException: @Bean method ShiroConfig.cacheManager called as a bean ref ...

  9. MySQL的安装及使用教程

    MySQL的安装及使用教程 一.  MySQL的下载及安装 首先登陆MySQL的官网,选择Downloads→Windows→MySQL Installer→Windows(x86,32-bit),M ...

  10. 手动脱KBys Packer(0.28)壳实战

    作者:Fly2015 吾爱破解培训第一课选修作业第5个练习程序.在公司的时候用郁金香OD调试该加壳程序的时候出了点问题,可是回家用吾爱破解版的OD一调试,浑身精神爽,啥问题也没有. 首先使用查壳工具对 ...