爬虫之 爬取京东计算机书籍
爬取京东的计算机类书籍
1. 工具: requests, pycharm, scrapy, mongodb
2. 网页提取工具: xpath
1. 分析京东网页:
打开京东网站 查看源码发现不是动态网页,而且都是列表, 说明了很好处理;开始分析;
我们只要提取书名,书的链接, 书的出版社,书的作者,评价数,价格
I
注意一下,书的价格, 评论数,源码并没有,说明是ajax请求;因此使用浏览器抓包看看有没有;
抓包可以找到评论数;
url: https://club.jd.com/comment/productCommentSummaries.action?my=pinglun&referenceIds=11936238
referenceIds书的id 返回是json
再找价格:
也可以找到:其中m 是书的原价, p 是当前的价格;
url: https://p.3.cn/prices/mgets?ext=11000000&pin=&type=1&area=1_72_4137_0&skuIds=J_11936238
skuIds是书的id, 返回是json
2. 编写代码:
scrapy startproject jd
1. 编写spider:
# coding: utf-8
import time
from scrapy.selector import Selector
from scrapy.http import Request
from scrapy.spiders import Spider
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning# 禁用安全请求警告
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
'''
time: 2018-05-19
by: jianmoumou233
爬取京东图书,IT分类'''class Page(Spider):name = "jd"mongo_collections = "jd"headers = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8','Accept-Language': 'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',"Upgrade-Insecure-Requests": "1","Connection": "keep-alive","Cache-Control": "max-age=0",}def start_requests(self):for i in xrange(1, 280):url = 'https://list.jd.com/list.html?cat=1713,3287,3797&page=%d' % iyield Request(url, dont_filter=True)def parse(self, response):''':param url: url:param title: book's name:param author: book's author:param shop: shop's name:param _id: book id and mongodb's _id:param price: book's price:param old_price: book's original price:param comment_count: book's number of comments'''xbody = Selector(response)item = dict()_li = xbody.xpath("//*[@id='plist']/ul/li")for i in _li:item['url'] = i.xpath("./div/div[1]/a/@href").extract_first()item['title'] = i.xpath("./div/div[contains(@class,'p-name')]/a/em/text()").extract_first()item['author'] = i.xpath("./div/div[contains(@class,'p-bookdetails')]//span[contains(@class,'author_type_1')]/a/text()").extract_first()item['shop'] = i.xpath("./div/div[contains(@class,'p-bookdetails')]/span[contains(@class,'p-bi-store')]/a/@title").extract_first()item["_id"] = i.xpath("./div/@data-sku").extract_first()item["spidertime"] = time.strftime("%Y-%m-%d %H:%M:%S")for k, v in item.items():if v:item[k] = str(v).strip()if item.get('_id'):try:item['price'], item["old_price"] = self.price(item['_id'], self.headers)time.sleep(2)item['comment_count'] = self.buy(item['_id'], self.headers)except Exception as e:print eif not str(item['url']).startswith("http"):item['url'] = "https" + item['url']yield item@staticmethoddef price(id, headers):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" % iddata = requests.get(url, headers=headers, verify=False).json()return data[0].get('p'), data[0].get("m")@staticmethoddef buy(id, headers):url = 'https://club.jd.com/comment/productCommentSummaries.action?my=pinglun&referenceIds=%s' % iddata = requests.get(url, headers=headers, verify=False).json()return data.get('CommentsCount')[0].get("CommentCount")
2. 编写入库(Mongodb)pipelines:
# -*- coding: utf-8 -*-import sys
import pymongo
reload(sys)
sys.setdefaultencoding("utf-8")class Mongo(object):mongo_uri = Nonemongo_db = Noneclient = Nonedb = Nonedef __init__(self, mongo_uri, mongo_db):self.mongo_uri = mongo_uriself.mongo_db = mongo_db@classmethoddef from_crawler(cls, crawler):return cls(mongo_uri=crawler.settings.get('MONGO_URI'),mongo_db=crawler.settings.get('MONGO_DATABASE', 'test'),)def open_spider(self, spider):self.client = pymongo.MongoClient(host=self.mongo_uri)self.db = self.client[self.mongo_db]def close_spider(self, spider):self.client.close()def process_item(self, item, spider):try:self.db[spider.mongo_collections].insert(dict(item))except Exception as e:pass# return item
3. 设置settings:
MONGO_URI = "mongodb://127.0.0.1:27017"
MONGO_DATABASE = "jd"# Configure item pipelines
# See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {'jd.pipelines.Mongo': 300,
}
4. 运行spider:
scrapy crawl jd
5. 结果:
url 的链接应该是https,我拼接错了;
总结:
爬了几千个,还没有封我,加上延迟,headrs尽量都加上;
爬虫之 爬取京东计算机书籍相关推荐
- 爬虫利器Pyppeteer的介绍和使用 爬取京东商城书籍信息
提起 selenium 想必大家都不陌生,作为一款知名的 Web 自动化测试框架,selenium 支持多款主流浏览器,提供了功能丰富的API 接口,经常被我们用作爬虫工具来使用.但是 seleniu ...
- 爬虫利器Pyppeteer的介绍和使用 爬取京东商城书籍信息!
提起 selenium 想必大家都不陌生,作为一款知名的 Web 自动化测试框架,selenium 支持多款主流浏览器,提供了功能丰富的API 接口,经常被我们用作爬虫工具来使用.但是 seleniu ...
- python学爬虫书籍_Python3实战爬虫之爬取京东图书的图文详解
最近在学习python3,下面这篇文章主要给大家介绍了关于Python3实战爬虫之爬取京东图书图片的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下 ...
- python爬取京东python书籍信息
python爬取京东python书籍信息 直接上代码镇宅......................... 需要用到的库:requests lxml pymongo 需要安装这些库,并且配置好mong ...
- python爬虫实例手机_Python爬虫实现爬取京东手机页面的图片(实例代码)
实例如下所示: __author__ = 'Fred Zhao' import requests from bs4 import BeautifulSoup import os from urllib ...
- java爬虫京东商品,Java爬虫实现爬取京东上的手机搜索页面 HttpCliient+Jsoup
1.需求及配置 需求:爬取京东手机搜索页面的信息,记录各手机的名称,价格,评论数等,形成一个可用于实际分析的数据表格. 使用maven项目,log4j记录日志,日志仅导出到控制台. maven依赖如下 ...
- 爬虫初学——爬取京东商品的评论(一)
最近,初学了一些爬虫的知识,然后刚好被老师要求去爬取一些评论数据(淘宝.京东等),来进行深度学习识别虚假评论.然后咋办咧,东搜搜西搜搜,看有没有什么好的办法.毕竟之前可是被反爬机制很强的网站弄得毫无头 ...
- 爬虫学习:爬取京东图书
爬虫学习:scrapy爬取京东图书,详情页url地址对应的响应并不能满足数据提取的需要price字段(即当前url地址对应的响应与element中不一样存在缺失,所以需要构造能够获取价格的请求) # ...
- Java实现网络爬虫:爬取京东商品案例
Java实现网络爬虫 爬取京东商品案例 需求分析 代码实现 爬取京东商品案例 需求分析 一.需求 抓取京东商城的数据,把商品数据保存到数据库. 二.功能分析 使用HttpClient发送一个get请求 ...
最新文章
- 《IBM-PC汇编语言程序设计》(第2版)【沈美明 温冬婵】——第四章——自编解析与答案
- leetcode 509. 斐波那契数(dfs)
- 仿京东账户设置APP模板
- 【今日CS 视觉论文速览】 9 Jan 2019
- Linux操作系统RedHat6.5安装
- node sqlite 插入数据_方便且实用,Python内置的轻量级数据库实操
- switch开关 ~ 学习记录
- 6.RabbitMQ实战 --- 从故障中恢复
- IIS下载无后缀文件的设置
- 计算机上数字代表那个音符,音符时值
- 2018年最值得投资的十大行业版图
- 解决多次点击出现蓝色背景
- 2019JAVA面试题附答案
- 最佳开源PHP开发工具
- Android手机与PC端进行通信
- LeetCode1221.分割平衡字符串1894.找到需要补充粉笔的学生编号(C++)
- 杰理之MIDI音乐实现【篇】
- python输入多个整数 输入quit表示结束_Python Selenium 之关闭窗口close与quit的方法
- Nokia S60系统问题:正常接收手机短信、但无法接收ISP短信(10086、携程、招行)
- Python for Maya DCC工具插件开发学习记录(一)