爬取淘宝

##爬取淘宝

使用爬虫框架scrapy爬取淘宝

###一.创建项目

1.安装scrapypip install scrapy

2.选择一个目录开启一个scrapy项目scrapy startproject taobao

3.新建一个名为mytaobao的爬虫scrapy genspider mytaobao taobao.com

二.制定需要的内容

从web端找到几项内容

1
2
3
4
5
6
价格:price
收货人数:sales
商品名:title
商铺名:nick
发货地址:loc
详情连接:detail_url

将内容写入items.py

根据提示开始写

1
2
# define the fields for your item here like:
# name = scrapy.Field()
1
2
3
4
5
6
7
class TaobaoItem(scrapy.Item):
price = scrapy.Field()
sales = scrapy.Field()
title = scrapy.Field()
nick = scrapy.Field()
loc = scrapy.Field()
detail_url = scrapy.Field()

三.分析url

淘宝搜索`女装 裙且按销量排序后的url为:

https://s.taobao.com/search?q=%E5%A5%B3%E8%A3%85+%E8%A3%99&imgfile=&js=1&stats_click=search_radio_all%3A1&initiative_id=staobaoz_20180406&ie=utf8&sort=sale-desc

大胆的删除一些看上去没啥用的内容

https://s.taobao.com/search?q=女装+裙&sort=sale-desc&s=44

所以:

1
2
3
4
q:关键字
sort:排序方式
sale-desc:销量降序
s:展示个数

在settings中增加常量:

1
2
3
KEY_WORDS = '女装 裙' #关键字
PAGE_NUM = 100 #页数
ONE_PAGE_COUNT = 44 #每页个数
1
2
3
4
5
6
7
8
9
10
11
12
base_url = 'https://s.taobao.com/search?q=%s&sort=sale-desc&s=%s'
def start_requests(self):
# 为了方便管理,统一将常量放在setting.py文件中
key_words = self.settings['KEY_WORDS']
# 分析页面可以得到关键字传入内容会进行转码且空格会替换为+
key_words = parse.quote(key_words, ' ').replace(' ', '+')
page_num = self.settings['PAGE_NUM']
one_page_count = self.settings['ONE_PAGE_COUNT']
for i in range(page_num):
url = self.base_url % (key_words, i * one_page_count)
# 将url传入生成器跳转到parse函数
yield scrapy.Request(url, callback=self.parse)

四.使用正则表达式解析

页面查看发现存在一段jsong_page_config其中包含了所要的内容

对其进行正则解析

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def parse(self, response):
# 使用scrapy内置的正则获取需要的内容
p = 'g_page_config = ({.*?});'
g_page_config = response.selector.re(p)[0]
g_page_config = json.loads(g_page_config)
auctions = g_page_config['mods']['itemlist']['data']['auctions']
for auction in auctions:
item = TaobaoItem() # 实例化item
item['price'] = auction['view_price']
item['sales'] = auction['view_sales']
item['title'] = auction['raw_title']
item['nick'] = auction['nick']
item['loc'] = auction['item_loc']
item['detail_url'] = auction['detail_url']

yield item # 将item传给生成器

五.数据存储到文件中

在pipelines中写入存储文件的语句

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import json
class TaobaoPipeline(object):

def open_spider(self,spider):
#打开文件,编码为utf-8
self.file = open('taobao.json','w',encoding='utf-8')
def process_item(self, item, spider):
#将item转换为字典且不修改编码,写入文件
content = json.dumps(dict(item),ensure_ascii=False) + '\n'
self.file.write(content)
return item
def close_spider(self,spider):
#关闭文件
self.file.close()

六.运行爬虫

使用:scrapy crawl mytaobao开始运行爬虫

 wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!
您的支持将鼓励我继续创作!