利用Python通過商品條形碼查詢商品信息的實現(xiàn)示例
提前說明,由于博文重在講解,代碼一體性有一定程度的破壞。如想要省事需要完整代碼請至一下鏈接下載:完整代碼下載
一 商品條形碼
平日大家會購買許許多多的商品,無論是飲料、食品、藥品、日用品等在商品的包裝上都會有條形碼。
商品條形碼包括零售商品、非零售商品、物流單元、位置的代碼和條碼標識。我國采用國際通用的商品代碼及條碼標識體系,推廣應用商品條形碼,建立我國的商品標識系統(tǒng)。
零售商品是指在零售端通過POS掃描結算的商品。其條碼標識由全球貿易項目代碼(GTIN)及其對應的條碼符號組成。零售商品的條碼標識主要采用EAN/UPC條碼。一聽啤酒、一瓶洗發(fā)水和一瓶護發(fā)素的組合包裝都可以作為一項零售商品賣給最終消費者。
總的來講就是每一種在市面流通的商品都會有屬于自己商品條形碼。

二 查詢商品條形碼的目的
從技術方面來講,本次利用Python通過商品條形碼查詢商品信息是為了練習爬蟲技術。
從生活方面來講,本次項目可以查詢購買商品的信息,確保商品來源與成分可靠。
三 Python實現(xiàn)
3.1 爬取網(wǎng)站介紹
網(wǎng)站鏈接如下:條形碼查詢網(wǎng)站
網(wǎng)站截圖如下:

可以看到在該網(wǎng)站中輸入某一商品的條形碼,后輸入驗證碼。點擊查詢即可查詢到商品信息。以“6901028001915”為例,進行一次查詢,截圖如下:

3.2 python代碼實現(xiàn)
3.2.1 日志模塊
為保存操作記錄在項目中添加日志模塊,代碼如下:
import logging
import logging.handlers
'''
日志模塊
'''
LOG_FILENAME = 'msg_seckill.log'
logger = logging.getLogger()
def set_logger():
logger.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(process)d-%(threadName)s - '
'%(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s')
console_handler = logging.StreamHandler()
console_handler.setFormatter(formatter)
logger.addHandler(console_handler)
file_handler = logging.handlers.RotatingFileHandler(
LOG_FILENAME, maxBytes=10485760, backupCount=5, encoding="utf-8")
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
set_logger()
3.2.2 查詢模塊
有上面的截圖可以看到,網(wǎng)站查詢需要數(shù)字驗證碼驗證,因此這里使用ddddocr包來識別驗證碼。導入相應的包:
from logging import fatal import ddddocr import requests import json import os import time import sys from msg_logger import logger
接下來是項目的主體代碼,整個操作邏輯代碼注釋中有詳細講解:
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36'}
path = os.path.abspath(os.path.dirname(sys.argv[0]))
# json化
def parse_json(s):
begin = s.find('{')
end = s.rfind('}') + 1
return json.loads(s[begin:end])
# 創(chuàng)建目錄
def mkdir(path):
# 去除首位空格
path = path.strip()
# 去除尾部 \ 符號
path = path.rstrip("\\")
# 判斷路徑是否存在
isExists=os.path.exists(path)
# 判斷結果
if not isExists:
os.makedirs(path)
logger.info(path + ' 創(chuàng)建成功')
return True
else:
# 如果目錄存在則不創(chuàng)建,并提示目錄已存在
logger.info(path + ' 目錄已存在')
return False
# 爬取 "tiaoma.cnaidc.com" 來查找商品信息
def requestT1(shop_id):
url = 'http://tiaoma.cnaidc.com'
s = requests.session()
# 獲取驗證碼
img_data = s.get(url + '/index/verify.html?time=', headers=headers).content
with open('verification_code.png','wb') as v:
v.write(img_data)
# 解驗證碼
ocr = ddddocr.DdddOcr()
with open('verification_code.png', 'rb') as f:
img_bytes = f.read()
code = ocr.classification(img_bytes)
logger.info('當前驗證碼為 ' + code)
# 請求接口參數(shù)
data = {"code": shop_id, "verify": code}
resp = s.post(url + '/index/search.html',headers=headers,data=data)
resp_json = parse_json(resp.text)
logger.info(resp_json)
# 判斷是否查詢成功
if resp_json['msg'] == '查詢成功' and resp_json['json'].get('code_img'):
# 保存商品圖片
img_url = ''
if resp_json['json']['code_img'].find('http') == -1:
img_url = url + resp_json['json']['code_img']
else:
img_url = resp_json['json']['code_img']
try:
shop_img_data = s.get(img_url, headers=headers, timeout=10,).content
# 新建目錄
mkdir(path + '\\' + shop_id)
localtime = time.strftime("%Y%m%d%H%M%S", time.localtime())
# 保存圖片
with open(path + '\\' + shop_id + '\\' + str(localtime) +'.png','wb') as v:
v.write(shop_img_data)
logger.info(path + '\\' + shop_id + '\\' + str(localtime) +'.png')
except requests.exceptions.ConnectionError:
logger.info('訪問圖片URL出現(xiàn)錯誤!')
if resp_json['msg'] == '驗證碼錯誤':
requestT1(shop_id)
return resp_json
3.2.3 運行結果
if __name__ == "__main__":
try:
dict_info = requestT1('6901028001915')['json']
print(dict_info['code_sn'])
print(dict_info['code_name'])
print(dict_info['code_company'])
print(dict_info['code_address'])
print(dict_info['code_price'])
except:
print('商品無法查詢!')
嘗試運行代碼,以“6901028001915”為例,查看運行結果:

可見商品的信息成功查詢出來。
到此這篇關于利用Python通過商品條形碼查詢商品信息的文章就介紹到這了,更多相關利用Python通過商品條形碼查詢商品信息內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
ipython jupyter notebook中顯示圖像和數(shù)學公式實例
這篇文章主要介紹了ipython jupyter notebook中顯示圖像和數(shù)學公式實例,具有很好的參考價值,希望對有所幫助。一起跟隨小編過來看看吧2020-04-04
python 執(zhí)行文件時額外參數(shù)獲取的實例
今天小編就為大家分享一篇python 執(zhí)行文件時額外參數(shù)獲取的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-12-12

