Python爬取京东的机器学习类图书的信息

  • 一,配置搜索关键字和页数,
  • 二,查找用到的三个URL的过程
    • 1. 搜索图书的URL
    • 2. 评论总数,差评数,好评数的URL
    • 3. 当前价格与打折前价格URL
  • 四,代码分析
  • 五,完整代码
  • 六, 执行结果

一,配置搜索关键字和页数,

本例是搜索”机器学习“,页数我配了100页没封号。大概爬下来三千条图书。用时没有留意,大概就几分钟吧,很快的。

if __name__ == '__main__':# 测试, 只爬取两页搜索页与两页评论test = CrawlDog('机器学习')test.main(2)test.store_xsl()

二,查找用到的三个URL的过程

1. 搜索图书的URL

https://search.jd.com/Search?keyword=%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0&enc=utf-8&suggest=1.his.0.0&wq=&pvid=d73028f8cf3e46deb44d843ef082fcef

2. 评论总数,差评数,好评数的URL

F12 --> NetWork , 在机器学习搜索页面往下拖鼠标,你会看到有好多图片的加载或Json请求,
其中就有异步评论数的请求。

https://club.jd.com/comment/productCommentSummaries.action?referenceIds=69957954609,33316347153,20445809140,11166079878,40853170920&callback=jQuery4865124&_=1593055042908

在url里把 &callback=jQuery4865124去掉,因为加上的话就会有jQuery4865124这个字出现,

https://club.jd.com/comment/productCommentSummaries.action?referenceIds=69957954609,33316347153,20445809140,11166079878,40853170920&_=1593055042908

3. 当前价格与打折前价格URL

找的步骤和评论数的总结的那个URL一样的。

四,代码分析

主要包括三个方法
crawl_message() 爬取商品的基本信息,爬完后调用comments()和prices()方法
comments() 爬取( 总评数,平均得分,好评数,默认好评,好评率,追评数,视频晒单数,差评数,中评数)
prices() 爬取当前商品的价格,打折前的商品价格
store_xsl() 爬完后 存放到excel表格里

五,完整代码

import requests
from lxml import etree
from concurrent import futures
import jsonimport pandas as pdclass CrawlDog:comment_headers = {'Referer': 'https://item.jd.com/%s.html' % 12615065,'Accept-Charset': 'utf-8','accept-language': 'zh,en-US;q=0.9,en;q=0.8,zh-TW;q=0.7,zh-CN;q=0.6','User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) ''Chrome/74.0.3729.169 Safari/537.36'}def __init__(self, keyword):"""初始化:param keyword: 搜索的关键词"""self.keyword = keywordself.data = pd.DataFrame()def crawl_message(self, page):"""从搜索页获取相应信息并存入数据库:param page: 搜索页的页码"""url = 'https://search.jd.com/Search?keyword={}&enc=utf-8&page={}&s={}'.format(self.keyword, page, (page-1)*30+1)index_headers = {'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,''application/signed-exchange;v=b3','accept-encoding': 'gzip, deflate, br','Accept-Charset': 'utf-8','accept-language': 'zh,en-US;q=0.9,en;q=0.8,zh-TW;q=0.7,zh-CN;q=0.6','user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) ''Chrome/74.0.3729.169 Safari/537.36'}rsp = requests.get(url=url, headers=index_headers).content.decode()print(url)# print(rsp)rsp = etree.HTML(rsp)items = rsp.xpath('//li[contains(@class, "gl-item")]')ids = []for item in items:try:info = dict()p_name = item.xpath('.//div[@class="p-name"]/a/em')info['title'] = etree.tostring(p_name[0], method='text', encoding='unicode').replace('\r','').replace('\n','').replace('\t','')info['price'] = item.xpath('.//div[@class="p-price"]//i/text()')[0]info['shop'] = item.xpath('.//div[@class="p-shopnum"]//a/text()')[0]info['icon'] = item.xpath('.//div[@class="p-icons"]//i/text()')info['url'] = 'https:' + item.xpath('.//div[@class="p-name"]/a/@href')[0]info['item_id'] = info.get('url').split('/')[-1][:-5]book_details= item.xpath('.//div[@class="p-bookdetails"]//span/a')info['author'] = etree.tostring(book_details[0], method='text', encoding='unicode').replace('\r','').replace('\n','').replace('\t','')info['publish_date'] = item.xpath('.//div[@class="p-bookdetails"]//span[@class="p-bi-date"]/text()')#info['price_'] = 0info['old_price'] = 0info['commentCount'] = 0info['averageScore'] = 0info['goodCount'] = 0info['defaultGoodCount'] = 0info['goodRate'] = 0info['afterCount'] = 0info['videoCount'] = 0info['poorCount'] = 0info['generalCount'] = 0ids.append(info['item_id'])self.data = self.data.append(info, ignore_index=True)# 实际爬取过程中有一些广告, 其中的一些上述字段为空except IndexError:print('item信息不全, drop!')continueprint(len(ids))self.comments(ids)self.prices(ids)def comments(self, ids):ids = ','.join([str(id) for id in ids])url = 'https://club.jd.com/comment/productCommentSummaries.action?my=pinglun&referenceIds={}'.format(ids)comments = requests.get(url=url, headers=self.comment_headers).json()print(ids)print(comments)# 总评数,平均得分,好评数,默认好评,好评率,追评数,视频晒单数,差评数,中评数comments_columns = ['commentCount', 'averageScore', 'goodCount', 'defaultGoodCount', 'goodRate','afterCount', 'videoCount', 'poorCount', 'generalCount']for comment in  comments["CommentsCount"]:comments_data= [comment["CommentCount"], comment["AverageScore"], comment["GoodCount"], comment["DefaultGoodCount"],comment["GoodRate"], comment["AfterCount"],comment["VideoCount"], comment["PoorCount"],comment["GeneralCount"]]#print(self.data.loc[self.data.item_id == str(comment['SkuId']), comments_columns])self.data.loc[self.data.item_id == str(comment['SkuId']), comments_columns] = comments_datadef prices(self, ids):str_ids = ','.join(['J_'+str(id) for id in ids])url = "https://p.3.cn/prices/mgets?ext=11000000&pin=&type=1&area=1_72_4137_0&skuIds=J_%s&pdbp=0&pdtk=&pdpin=&pduid=15229474889041156750382&source=list_pc_front" % str_idsprices = requests.get(url, headers=self.comment_headers).json()for price in prices:#self.data.loc[self.data.item_id == price['id'][2:], 'price_'] = price.get('p')self.data.loc[self.data.item_id == price['id'][2:], 'old_price'] = price.get("m")def main(self, index_pn):"""实现爬取的函数:param index_pn: 爬取搜索页的页码总数:return:"""# 爬取搜索页函数的参数列表#il = [i * 2 + 1 for i in range(index_pn)]il = [i +1 for i in range(index_pn)]#print(il)# 创建一定数量的线程执行爬取with futures.ThreadPoolExecutor(3) as executor:executor.map(self.crawl_message, il)#for i in range(index_pn):#self.get_index(i+1)def store_xsl(self):self.data.to_csv( 'data.csv', encoding = 'utf-8', index=False)def get_comments__top_100(self):df = pd.read_csv('final_data_attach_comment.csv', encoding='utf-8')ids =df[df.isnull().T.any()]['item_id'].tolist()print(len(ids))index_headers = {'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,''application/signed-exchange;v=b3','accept-encoding': 'gzip, deflate, br','Accept-Charset': 'utf-8','accept-language': 'zh,en-US;q=0.9,en;q=0.8,zh-TW;q=0.7,zh-CN;q=0.6','user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) ''Chrome/74.0.3729.169 Safari/537.36'}i = 0for id in ids:i = i + 1if i > 10: breakurl = "https://club.jd.com/comment/productPageComments.action?productId=%s&score=0&sortType=5&page=0&pageSize=10&isShadowSku=0&fold=1" % idtry:comments_json = requests.get(url, headers=index_headers).json()print(comments_json, ' dd')comment_str = ''for comment_json in comments_json['comments']:comment_str = comment_str + comment_json['content'] + '|'df.loc[df.item_id == id, 'comment'] = comment_strprint(comment_str)except json.decoder.JSONDecodeError:print('item信息不全, drop!', id)continuefinally:df.to_csv('final_data_attach_comment.csv', encoding='utf-8', index=False)df.to_csv('final_data_attach_comment.csv', encoding='utf-8', index=False)if __name__ == '__main__':# 测试, 只爬取两页搜索页与两页评论test = CrawlDog('机器学习')test.main(100)test.store_xsl()#test.get_comments__top_100()

六, 执行结果

[爬虫-python]爬取京东100页的图书(机器学习)的信息(价格,打折后价格,书名,作者,好评数,差评数,总评数)相关推荐

  1. 爬虫——python爬取京东商品用户评价

    以小米手环7为例,分别爬取小米手环7用户评价中的好评.中评.差评 使用工具:PyCharm Community 需要python库:requests 安装方法:File-->Settings-- ...

  2. python爬虫实例手机_Python爬虫实现爬取京东手机页面的图片(实例代码)

    实例如下所示: __author__ = 'Fred Zhao' import requests from bs4 import BeautifulSoup import os from urllib ...

  3. python爬虫用什么电脑好_【Python】【爬虫】最近想买电脑,用Python爬取京东评论做个参考...

    最近想换电脑,又有点不确定买哪一款.所以决定爬取京东上电脑评论,做个参考,并把最终结果绘制成词云图. 一.先来看下三款电脑评价的词云图 1 用Python爬取京东自营ThinkPad T490s的评论 ...

  4. python学爬虫书籍_Python3实战爬虫之爬取京东图书的图文详解

    最近在学习python3,下面这篇文章主要给大家介绍了关于Python3实战爬虫之爬取京东图书图片的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下 ...

  5. 【Python爬虫】最近想买电脑,用Python爬取京东评论做个参考

      最近想换电脑,又有点不确定买哪一款.所以决定爬取京东上电脑评论,做个参考,并把最终结果绘制成词云图.    一.先来看下三款电脑评价的词云图    1 用Python爬取京东自营ThinkPad ...

  6. Python爬虫教程:Python爬取京东商城商品大图详解

    Python爬取京东商城商品大图详解 做为一个爬虫初学者,在做爬取网址图片的练习中以京东网为例爬取商品大图并保存在相应的文件夹 1.导入模块 import urllib.request import ...

  7. Python爬取京东回力鞋购买情况看看码数比例

    背景 突然想起前阵子看到一篇爬bar并统计女生罩杯情况的文章,心想.我擦,这么好的题材让别人先写了我风暴哭泣.心想,算了,人家本来就比我优秀.然后随便去京东逛了逛.看到回力旗舰店给我推了,那我也来搞搞 ...

  8. python爬取京东商品数据要先登录_手把手教你用python 爬取京东评论

    本次python实战,主要目标是利用 Python爬取京东商品评论数,如上图所示:爬取"Python之父"推荐的小蓝书,这些信息主要包括用户名.书名.评论等信息. 爬取的网址url ...

  9. python爬取京东python书籍信息

    python爬取京东python书籍信息 直接上代码镇宅......................... 需要用到的库:requests lxml pymongo 需要安装这些库,并且配置好mong ...

最新文章

  1. LeetCode 583. Delete Operation for Two Strings--动态规划 DP--Java,Python,C++解法
  2. RecyclerView Adapter 所使用的数据list发生变化需要注意的事情
  3. Spring提取@Transactional事务注解的源码解析
  4. startActivityForResult()
  5. iNeuOS工业互联网,增加一批PLC、核工业、数字模块、传感器等设备驱动
  6. Mac不装软件校验MD5和SHA1值
  7. 流水灯verilog实验原理_IC设计实例解析之“流水线技术”
  8. jquery将表单序列化json对象
  9. 在CentOS7上安装vim编辑器报错无法解析阿里云主机
  10. 车辆贷款违约预测 Top1(2021科大讯飞)
  11. 联想硬盘保护系统破解及电脑常见密码破解总结
  12. 我在51CTO微职位学PMP_飘过攻略及心得分享
  13. 九、障碍罚函数法---内点、外点罚函数
  14. 基于Simulink的转速、电流双闭环直流调速系统的建模与仿真
  15. 最适合程序员的笔记软件
  16. Qt数据库应用18-横向纵向排版
  17. NAS自回血方案介绍
  18. Dell H300/6i/6iR/H700/H800阵列卡配置(转)
  19. 【ML】MoG与EM:从MoG到EM
  20. 张欲莎-老公,不要停。。。

热门文章

  1. 【斗医】【3】Web应用开发20天
  2. DBUtils 主要结果集说明
  3. vs的form标签引起css走样问题
  4. Java面试技巧—如何自我介绍
  5. Oracle dbms_random随机函数包
  6. CentOS 新增swap交换空间
  7. 消息队列面试 - 如何保证消息的可靠性传输?
  8. CCNA初认识——ACL命令
  9. C语言,利用求余运算拆分三位数的个,十,百位数字,并求和
  10. Js Vue 对象数组的创建方式