用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 ...
随机推荐
- Windows10安装NTP服务器
步骤1:打开注册表 步骤2:打开注册表中[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\Config\AnnounceFla ...
- Typescript中的类 Es5中的类和静态方法和继承(原型链继承、对象冒充继承、原型链+对象冒充组合继承)
<!doctype html> <html> <head> <meta charset="utf-8"> <meta name ...
- 【转】Python常见web系统返回码
responses = { 100: ('Continue', 'Request received, please continue'), 101: ('Switching Protocols', ' ...
- 123457123457#0#-----com.tym.YuErBaiKeTYM--前拼后广--育儿百科
com.tym.YuErBaiKeTYM--前拼后广--育儿百科
- 一个php创建webservice,并通过c#调用的真实实例(转)
https://www.cnblogs.com/sequh/archive/2015/09/18/4819832.html 最近需要用php创建webservice供C#和JAVA来调用,通过3天的搜 ...
- Sound (audio file) player in java - working source code example
转载自:http://ganeshtiwaridotcomdotnp.blogspot.com/2011/12/sound-audio-file-player-in-java-working.html ...
- 04点睛Spring4.1-资源调用
转发:https://www.iteye.com/blog/wiselyman-2210666 4.1 Resource spring用来调用外部资源数据的方式 支持调用文件或者是网址 在系统中调用p ...
- Cas(03)——Cas Server中各配置文件介绍
Cas Server中各配置文件介绍 Cas Server中所有的配置文件都是放在WEB-INF目录及其子目录下的. 在WEB-INF/classes下的配置文件有: l cas-theme-def ...
- git的使用学习(三)时光机穿梭
1.版本回退 现在,你已经学会了修改文件,然后把修改提交到Git版本库,现在,再练习一次,修改readme.txt文件如下: Git is a distributed version control ...
- windows强大的快捷键
1 电脑锁屏 有些时候,需要暂时离开座位去处理其他事,可是电脑还有数据再跑. 关掉的话,数据就白跑了,不关的话,又不想让别人看到我电脑的资料. 那么就按住windows键后,再按L键. 这样电脑就直接 ...