# -*- 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. 1.13 Python基础知识 - 字典和集合

    一.字典 字典是一组键-值对的数据结构.每个键对应一个值.在字典中,键不能重复.根据键可以查询到值.字典是键和值的映射关系 字典的定义: 字典通过花括号中用逗号分隔的元素(键-值.键-值对使用冒号分隔 ...

  2. swiper轮播控件配置项

    var mySwiper = new Swiper ('.swiper-container', {    direction: 'horizontal',    loop: true,    auto ...

  3. input输入框获得、失去焦点添加事件

    onBlur:当输入框失去焦点后 onFocus:当输入框获得焦点后 这两个JavaScript事件是写在html标签中的例如: <input type="text" onB ...

  4. Java Web学习总结(13)——JSP入门

    一.什么是JSP? JSP全称是Java Server Pages,它和servle技术一样,都是SUN公司定义的一种用于开发动态web资源的技术. JSP这门技术的最大的特点在于,写jsp就像在写h ...

  5. μC/OS中的任务就绪表

    为了便于对就绪表的查找,μC/OSII又定义了一个数据类型为INT8U的变量OSRdyGrp, 并使该变量的每一位都对应OSRdyTbl[ ]的一个任务组(即数组的一个元素),如果某任务组中 有任务就 ...

  6. call.apply.冒充对象继承

    call方法:让调用对象执行,然后第一参数是谁.调用对象的this就改变,指向谁,后边跟参数,依次对应传入 apply方法:让调用对象执行,然后第一参数是谁.调用对象的this就改变指向是谁,后边跟参 ...

  7. DOM相关知识总结

    DOM相关: 1.获取DOM元素 document.getElementById document.getElementsByName document.getElementsByTagName do ...

  8. [D3] SVG Graphics Containers and Text Elements in D3 v4

    SVG is a great output format for data visualizations because of its scalability, but it comes with s ...

  9. Android java.lang.IllegalArgumentException: Object returned from onCreateLoader must not be a non-static inn

    AsyncTaskLoader: http://developer.Android.com/intl/zh-CN/reference/android/content/AsyncTaskLoader.h ...

  10. UVA 11280 - Flying to Fredericton SPFA变形

    http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&c ...