用scrapy爬取京东商城的商品信息
软件环境:
gevent (1.2.2)
greenlet (0.4.12)
lxml (4.1.1)
pymongo (3.6.0)
pyOpenSSL (17.5.0)
requests (2.18.4)
Scrapy (1.5.0)
SQLAlchemy (1.2.0)
Twisted (17.9.0)
wheel (0.30.0)
1.创建爬虫项目
2创建京东网站爬虫. 进入爬虫项目目录,执行命令:
scrapy genspider jd www.jd.com
会在spiders目录下会创建和你起的名字一样的py文件:jd.py,这个文件就是用来写你爬虫的请求和响应逻辑的
3. jd.py文件配置
https://search.jd.com/Search?
def start_requests(self):
# https://www.amazon.cn/s/ref=nb_sb_ss_i_1_6?field-keywords=macbook+pro
# 拼接处符合条件的URL地址
# 并通过scrapy.Requst封装请求,并调用回调函数parse_index处理,同时会把response传递给回调函数
url = 'https://search.jd.com/Search?'
# 拼接的时候field-keywords后面是不加等号的
url += urlencode({"keyword": self.keyword, "enc": "utf-8"})
yield scrapy.Request(url,
callback=self.parse_index,
)
def parse_detail(self, response):
"""
接收parse_index的回调,并接收response返回值,并解析response
:param response:
:return:
"""
jd_url = response.url
sku = jd_url.split('/')[-1].strip(".html")
# price信息是通过jsonp获取,可以通过开发者工具中的script找到它的请求地址
price_url = "https://p.3.cn/prices/mgets?skuIds=J_" + sku
response_price = requests.get(price_url)
# extraParam={"originid":"1"} skuIds=J_3726834
# 这里是物流信息的请求地址,也是通过jsonp发送的,但目前没有找到它的参数怎么获取的,这个是一个固定的参数,如果有哪位大佬知道,好望指教
express_url = "https://c0.3.cn/stock?skuId=3726834&area=1_72_4137_0&cat=9987,653,655&extraParam={%22originid%22:%221%22}"
response_express = requests.get(express_url)
response_express = json.loads(response_express.text)['stock']['serviceInfo'].split('>')[1].split('<')[0]
title = response.xpath('//*[@class="sku-name"]/text()').extract_first().strip()
price = json.loads(response_price.text)[0]['p']
delivery_method = response_express
# # 把需要的数据保存到Item中,用来会后续储存做准备
item = AmazonItem()
item['title'] = title
item['price'] = price
item['delivery_method'] = delivery_method # 最后返回item,如果返回的数据类型是item,engine会检测到并把返回值发给pipelines处理
return item
4. item.py配置
import scrapy class JdItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
# amazome Item
title = scrapy.Field()
price = scrapy.Field()
delivery_method = scrapy.Field()
5. pipelines.py配置
from pymongo import MongoClient class MongoPipeline(object):
"""
用来保存数据到MongoDB的pipeline
""" def __init__(self, db, collection, host, port, user, pwd):
"""
连接数据库
:param db: databaes name
:param collection: table name
:param host: the ip for server
:param port: thr port for server
:param user: the username for login
:param pwd: the password for login
"""
self.db = db
self.collection = collection
self.host = host
self.port = port
self.user = user
self.pwd = pwd @classmethod
def from_crawler(cls, crawler):
"""
this classmethod is used for to get the configuration from settings
:param crwaler:
:return:
"""
db = crawler.settings.get('DB')
collection = crawler.settings.get('COLLECTION')
host = crawler.settings.get('HOST')
port = crawler.settings.get('PORT')
user = crawler.settings.get('USER')
pwd = crawler.settings.get('PWD') return cls(db, collection, host, port, user, pwd) def open_spider(self, spider):
"""
run once time when the spider is starting
:param spider:
:return:
"""
# 连接数据库
self.client = MongoClient("mongodb://%s:%s@%s:%s" % (
self.user,
self.pwd,
self.host,
self.port
)) def process_item(self, item, spider):
"""
storage the data into database
:param item:
:param spider:
:return:
"""
# 获取item数据,并转换成字典格式
d = dict(item)
# 有空值得不保存
if all(d.values()):
# 保存到mongodb中
self.client[self.db][self.collection].save(d)
return item # 表示将item丢弃,不会被后续pipeline处理
# raise DropItem()
6. 配置文件
# database server
DB = "jd"
COLLECTION = "goods"
HOST = "127.0.0.1"
PORT = 27017
USER = "root"
PWD = ""
ITEM_PIPELINES = {
'MyScrapy.pipelines.MongoPipeline': 300,
}
用scrapy爬取京东商城的商品信息的更多相关文章
- Scrapy实战篇(八)之Scrapy对接selenium爬取京东商城商品数据
本篇目标:我们以爬取京东商城商品数据为例,展示Scrapy框架对接selenium爬取京东商城商品数据. 背景: 京东商城页面为js动态加载页面,直接使用request请求,无法得到我们想要的商品数据 ...
- 用scrapy爬取京东的数据
本文目的是使用scrapy爬取京东上所有的手机数据,并将数据保存到MongoDB中. 一.项目介绍 主要目标 1.使用scrapy爬取京东上所有的手机数据 2.将爬取的数据存储到MongoDB 环境 ...
- scrapy爬取全部知乎用户信息
# -*- coding: utf-8 -*- # scrapy爬取全部知乎用户信息 # 1:是否遵守robbots_txt协议改为False # 2: 加入爬取所需的headers: user-ag ...
- Scrapy实战篇(四)爬取京东商城文胸信息
创建scrapy项目 scrapy startproject jingdong 填充 item.py文件 在这里定义想要存储的字段信息 import scrapy class JingdongItem ...
- Scrapy实战篇(七)之Scrapy配合Selenium爬取京东商城信息(下)
之前我们使用了selenium加Firefox作为下载中间件来实现爬取京东的商品信息.但是在大规模的爬取的时候,Firefox消耗资源比较多,因此我们希望换一种资源消耗更小的方法来爬取相关的信息. 下 ...
- Scrapy实战篇(五)爬取京东商城文胸信息
创建scrapy项目 scrapy startproject jingdong 填充 item.py文件 在这里定义想要存储的字段信息 import scrapy class JingdongItem ...
- scrapy爬取京东iPhone11评论(一)
咨询行业中经常接触到文本类信息,无论是分词做词云图,还是整理编码分析用,都非常具有价值. 本文将记录使用scrapy框架爬取京东IPhone11评论的过程,由于一边学习一边实践,更新稍慢请见谅. 1. ...
- Python爬虫从入门到放弃(十八)之 Scrapy爬取所有知乎用户信息(上)
爬取的思路 首先我们应该找到一个账号,这个账号被关注的人和关注的人都相对比较多的,就是下图中金字塔顶端的人,然后通过爬取这个账号的信息后,再爬取他关注的人和被关注的人的账号信息,然后爬取被关注人的账号 ...
- Python爬虫从入门到放弃(十九)之 Scrapy爬取所有知乎用户信息(下)
在上一篇文章中主要写了关于爬虫过程的分析,下面是代码的实现,完整代码在:https://github.com/pythonsite/spider items中的代码主要是我们要爬取的字段的定义 cla ...
随机推荐
- flutter DataTable数据表格
数据表显示原始数据集.它们通常出现在桌面企业产品中.DataTable Widget实现这个组件 文档:https://api.flutter.dev/flutter/material/DataTab ...
- python 抓取数据 存入 excel
import requestsimport datetimefrom random import choicefrom time import timefrom openpyxl import loa ...
- CentOS7使用yum安装RabbitMQ
转自:https://jingyan.baidu.com/article/456c463b16f3820a583144a1.html 登录名:admin 密码:admin 1. 如果安装后web界 ...
- web端自动化——selenium3+Python3+pycharm自动化
1.前言: 对于初学者来说,python自带的IDLE,精简又方便,不过一个好的编辑器能让python编码变得更方便,更加优美些. 不过呢,也可以自己去下载其他更好用的代码编辑器,在这推荐: PyCh ...
- WPF TextBlock 文本换行的两种方式
第一种: <TextBlock> This is line 1.<LineBreak/> This is line 2. </TextBlock> 第二种 < ...
- 第八章 跨语言服务治理方案 Service Mesh
8.1 Service Mesh 概述 新兴的下一代微服务架构,被称为下一代微服务,同时也是云原生技术栈的代表技术之一. 8.1.1 Service Mesh的由来 从2016年到2018年,serv ...
- EM算法概念
EM算法是一种非常经典的alternative optimizing算法.alternative optimizing的思想就是对于一个最优化问题,可以计算分为两步或者参数分为两个,就可以随机任意的选 ...
- jvm误区--动态对象年龄判定
原文链接:https://blog.csdn.net/u014493323/article/details/82921740 虚拟机并不是永远地要求对象的年龄必须达到了MaxTenuringThres ...
- HTTP权威指南-URL与资源
URL与资源 URL是URI的子集 方案(http),主机(www.baidu.com),路径(/home/logo.png) 方案,其实有很多,HTTP.HTTPS.FTP,SMTP等等. http ...
- 【剑指offer】面试题 42. 连续子数组的最大和
面试题 42. 连续子数组的最大和 NowCoder 题目描述 输入一个整型数组,数组里有正数也有负数.数组中一个或连续的多个整数组成一个子数组.求所有子数组的和的最大值. 示例: 输入: [-2,1 ...