# -*- 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. pt支持的格式

  2. 【Codeforces Round #431 (Div. 2) C】From Y to Y

    [链接]点击打开链接 [题意] 让你构造一个大小最多为10W的字符multiset. 你进行n-1次操作; 每次操作,从set中取出两个字符串,一开始单个字符被认为是字符串. 然后把它们连接在一起. ...

  3. 2013腾讯编程马拉松初赛第〇场(HDU 4504)威威猫系列故事——篮球梦

    http://acm.hdu.edu.cn/showproblem.php?pid=4504 题目大意: 篮球赛假如我们现在已经知道当前比分 A:B,A代表我方的比分,B代表对方的比分,现在比赛还剩下 ...

  4. APP功能点测试

    一.移动互联网特点: 1,用户体验至上:精准的用户体验 2,核心竞争力:市场占有率和业务创新能力 3,营销模型:通过口碑传播吸引客户,随之参与互动(如分享等,对接口测试要求高) 二.项目特点: 1,开 ...

  5. java学习笔记之基础语法(一)

    1.java语言基础由关键字.标识符.注释.常量和变量.运算符.语句.函数和数组等组成. 2.1关键字 定义:被java语言赋予了特殊含义的单词 特点:关键字中所有的字母都是小写. 2.2用于定义数据 ...

  6. 9.8 Binder系统_c++实现_内部机制1

    1. 内部机制_回顾binder框架关键点 binder进程通讯过程情景举例: test_server通过addservice向service_manager注册服务 test_client通过get ...

  7. 【习题 5-6 UVA-1595】Symmetry

    [链接] 我是链接,点我呀:) [题意] 在这里输入题意 [题解] 每一个y坐标的点都找中点. 看看中点是不是都一样就好. [代码] #include <bits/stdc++.h> us ...

  8. KDE Plasma 5.8 的 LTS 周期正好与其所采用的 Qt 5.6 的 LTS 周期一致

    在 KDE Plasma 5.7 刚刚发布不久,KDE 开发团队就宣布了 KDE Plasma 5.8 的开发计划.这个版本将是一个 LTS 版本,据我所知,这应该是 KDE 历史上第一个 LTS 版 ...

  9. sql海量数据优化

    1.应尽量避免在 where 子句中对字段进行 null 值判断,否则将导致引擎放弃使用索引而进行全表扫描,如: select id from t where num is null 可以在num上设 ...

  10. [Angular2] Build reuseable template with ngTemplateOutlet

    We can build a template, use this template and pass in different context to make it reuseable: <t ...