软件环境:

 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文件配置

分析的amazon网站的url规则:
https://search.jd.com/Search?
以防关键字是中文,所以要做urlencode
        1.首先写一个start_request函数,用来发送第一次请求,并把请求结果发给回调函数parse_index,同时把reponse返回值传递给回调函数,response类型<class                 'scrapy.http.response.html.HtmlResponse'>
     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,
)
        2.parse_index从reponse中获取所有的产品详情页url地址,并遍历所有的url地址发送request请求,同时调用回调函数parse_detail去处理结果
 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爬取京东商城的商品信息的更多相关文章

  1. Scrapy实战篇(八)之Scrapy对接selenium爬取京东商城商品数据

    本篇目标:我们以爬取京东商城商品数据为例,展示Scrapy框架对接selenium爬取京东商城商品数据. 背景: 京东商城页面为js动态加载页面,直接使用request请求,无法得到我们想要的商品数据 ...

  2. 用scrapy爬取京东的数据

    本文目的是使用scrapy爬取京东上所有的手机数据,并将数据保存到MongoDB中. 一.项目介绍 主要目标 1.使用scrapy爬取京东上所有的手机数据 2.将爬取的数据存储到MongoDB 环境 ...

  3. scrapy爬取全部知乎用户信息

    # -*- coding: utf-8 -*- # scrapy爬取全部知乎用户信息 # 1:是否遵守robbots_txt协议改为False # 2: 加入爬取所需的headers: user-ag ...

  4. Scrapy实战篇(四)爬取京东商城文胸信息

    创建scrapy项目 scrapy startproject jingdong 填充 item.py文件 在这里定义想要存储的字段信息 import scrapy class JingdongItem ...

  5. Scrapy实战篇(七)之Scrapy配合Selenium爬取京东商城信息(下)

    之前我们使用了selenium加Firefox作为下载中间件来实现爬取京东的商品信息.但是在大规模的爬取的时候,Firefox消耗资源比较多,因此我们希望换一种资源消耗更小的方法来爬取相关的信息. 下 ...

  6. Scrapy实战篇(五)爬取京东商城文胸信息

    创建scrapy项目 scrapy startproject jingdong 填充 item.py文件 在这里定义想要存储的字段信息 import scrapy class JingdongItem ...

  7. scrapy爬取京东iPhone11评论(一)

    咨询行业中经常接触到文本类信息,无论是分词做词云图,还是整理编码分析用,都非常具有价值. 本文将记录使用scrapy框架爬取京东IPhone11评论的过程,由于一边学习一边实践,更新稍慢请见谅. 1. ...

  8. Python爬虫从入门到放弃(十八)之 Scrapy爬取所有知乎用户信息(上)

    爬取的思路 首先我们应该找到一个账号,这个账号被关注的人和关注的人都相对比较多的,就是下图中金字塔顶端的人,然后通过爬取这个账号的信息后,再爬取他关注的人和被关注的人的账号信息,然后爬取被关注人的账号 ...

  9. Python爬虫从入门到放弃(十九)之 Scrapy爬取所有知乎用户信息(下)

    在上一篇文章中主要写了关于爬虫过程的分析,下面是代码的实现,完整代码在:https://github.com/pythonsite/spider items中的代码主要是我们要爬取的字段的定义 cla ...

随机推荐

  1. PHP技术知识点整理

    1.解释mvc (1)mvc即 模型model,视图view,控制器controller:是一种模型,是一种编程思想,就是把一个应用的输入.输出.数据处理分开,分解耦合(2)A..视图,数据采集和处理 ...

  2. flutter DropdownButton使用

    import 'package:flutter/material.dart'; class MyStatefulWidget extends StatefulWidget { MyStatefulWi ...

  3. 【转载】 我的Machine Learning学习之路

    原文地址: https://www.cnblogs.com/steven-yang/p/5857964.html ------------------------------------------- ...

  4. OpenGL ES3使用MSAA(多重采样抗锯齿)的方法

    昨晚花费了我2个多小时的时间终于把OpenGL ES3.0中的MSAA给搞定了.在OpenGL ES2.0中,Khronos官方没有引入标准的MSAA全屏抗锯齿的方法,而Apple则采用了自己的GL_ ...

  5. Dart 中常用的数组操作方法总结

    这里总结了一些在 Dart 中常用的数组操作方法,以便查阅. 首先,我们准备两组数据,以方便后面使用: List<Map> students = [ { 'name': 'tom', 'a ...

  6. Wpf 关闭当前窗体 打开新窗体

    MainWindow mainWindow = new MainWindow("/pages/ProductionInfo/ProductionFacts.xaml"); Wind ...

  7. time zone list

    GMT UTC WET WET CET CET MET CET ECT CET EET EET MIT Pacific/Apia HST Pacific/Honolulu AST America/An ...

  8. jquery获取复选框checkbox的值

    jQuery API : each(callback) :以每一个匹配的元素作为上下文来执行一个函数. :checked :匹配所有选中的被选中元素(复选框.单选框等,不包括select中的optio ...

  9. 【Leetcode_easy】868. Binary Gap

    problem 868. Binary Gap solution1: class Solution { public: int binaryGap(int N) { ; vector<int&g ...

  10. UCOS III的时间片轮转调度的一个问题

    1. 如果当前一个任务A在时间片未到来之前,主动放弃剩下的时间片,进入下一个任务B,那么下一个任务的的执行时间是多久? 书上说,是重置时间片,也就是说任务B也运行一个完整的时间片.