python实现爬取千万淘宝商品的方法
作者:mingaixin 时间:2021-04-01 06:08:56
本文实例讲述了python实现爬取千万淘宝商品的方法。分享给大家供大家参考。具体实现方法如下:
import time
import leveldb
from urllib.parse import quote_plus
import re
import json
import itertools
import sys
import requests
from queue import Queue
from threading import Thread
URL_BASE = 'http://s.m.taobao.com/search?q={}&n=200&m=api4h5&style=list&page={}'
def url_get(url):
# print('GET ' + url)
header = dict()
header['Accept'] = 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
header['Accept-Encoding'] = 'gzip,deflate,sdch'
header['Accept-Language'] = 'en-US,en;q=0.8'
header['Connection'] = 'keep-alive'
header['DNT'] = '1'
#header['User-Agent'] = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.71 Safari/537.36'
header['User-Agent'] = 'Mozilla/12.0 (compatible; MSIE 8.0; Windows NT)'
return requests.get(url, timeout = 5, headers = header).text
def item_thread(cate_queue, db_cate, db_item):
while True:
try:
cate = cate_queue.get()
post_exist = True
try:
state = db_cate.Get(cate.encode('utf-8'))
if state != b'OK': post_exist = False
except:
post_exist = False
if post_exist == True:
print('cate-{}: {} already exists ... Ignore'.format(cate, title))
continue
db_cate.Put(cate.encode('utf-8'), b'crawling')
for item_page in itertools.count(1):
url = URL_BASE.format(quote_plus(cate), item_page)
for tr in range(5):
try:
items_obj = json.loads(url_get(url))
break
except KeyboardInterrupt:
quit()
except Exception as e:
if tr == 4: raise e
if len(items_obj['listItem']) == 0: break
for item in items_obj['listItem']:
item_obj = dict(
_id = int(item['itemNumId']),
name = item['name'],
price = float(item['price']),
query = cate,
category = int(item['category']) if item['category'] != '' else 0,
nick = item['nick'],
area = item['area'])
db_item.Put(str(item_obj['_id']).encode('utf-8'),
json.dumps(item_obj, ensure_ascii = False).encode('utf-8'))
print('Get {} items from {}: {}'.format(len(items_obj['listItem']), cate, item_page))
if 'nav' in items_obj:
for na in items_obj['nav']['navCatList']:
try:
db_cate.Get(na['name'].encode('utf-8'))
except:
db_cate.Put(na['name'].encode('utf-8'), b'waiting')
db_cate.Put(cate.encode('utf-8'), b'OK')
print(cate, 'OK')
except KeyboardInterrupt:
break
except Exception as e:
print('An {} exception occured'.format(e))
def cate_thread(cate_queue, db_cate):
while True:
try:
for key, value in db_cate.RangeIter():
if value != b'OK':
print('CateThread: put {} into queue'.format(key.decode('utf-8')))
cate_queue.put(key.decode('utf-8'))
time.sleep(10)
except KeyboardInterrupt:
break
except Exception as e:
print('CateThread: {}'.format(e))
if __name__ == '__main__':
db_cate = leveldb.LevelDB('./taobao-cate')
db_item = leveldb.LevelDB('./taobao-item')
orig_cate = '正装'
try:
db_cate.Get(orig_cate.encode('utf-8'))
except:
db_cate.Put(orig_cate.encode('utf-8'), b'waiting')
cate_queue = Queue(maxsize = 1000)
cate_th = Thread(target = cate_thread, args = (cate_queue, db_cate))
cate_th.start()
item_th = [Thread(target = item_thread, args = (cate_queue, db_cate, db_item)) for _ in range(5)]
for item_t in item_th:
item_t.start()
cate_th.join()
希望本文所述对大家的Python程序设计有所帮助。
标签:python,淘宝
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python爬虫爬取百度搜索内容代码实例
2022-06-23 02:21:11
python 按不同维度求和,最值,均值的实例
2023-06-12 15:08:23
![](https://img.aspxhome.com/file/2023/9/59479_0s.jpg)
一个数组随机不重复问题
2008-09-02 20:05:00
简单的水果风暴的算法过程
2009-12-13 15:49:00
JavaScript match() 方法
2007-11-04 13:28:00
golang中使用匿名结构体的方法
2023-07-10 07:26:56
SQL Server 2005返回刚刚插入的数据条目id值
2008-12-04 17:16:00
python实现复制大量文件功能
2023-09-03 16:42:54
在asp中通过vbs类实现rsa加密与解密
2010-05-27 12:18:00
用ASP实现IE地址栏参数的判断
2008-10-10 15:54:00
微信小程序开发工具介绍
2023-08-10 23:05:40
![](https://img.aspxhome.com/file/2023/1/58651_0s.jpg)
ubuntu系统下切换python版本的方法
2021-07-05 18:12:50
Python简单进程锁代码实例
2022-06-23 00:45:22
简单有效上手Python3异步asyncio问题
2022-01-14 02:28:34
![](https://img.aspxhome.com/file/2023/2/68422_0s.gif)
python版本单链表实现代码
2022-12-06 16:49:26
js断点调试心得分享(必看篇)
2023-07-06 22:13:25
![](https://img.aspxhome.com/file/2023/6/55896_0s.png)
Python学习之字典和集合的使用详解
2022-11-01 19:54:21
运行(runCode)复制(copyCode)保存(saveCode)代码框方法
2007-10-21 08:41:00
asp和php下textarea提交大量数据发生丢失的解决方法
2023-10-26 09:01:43
基于php权限分配的实现代码
2023-11-14 11:10:49
![](https://img.aspxhome.com/file/2023/3/94503_0s.png)