Python爬虫,京东自动登录,在线抢购商品

该博客介绍如何使用Python爬虫自动登录京东网站,监控商品库存和价格,并实现自动下单功能,辅助用户进行在线抢购。内容涵盖二维码扫码登录、Golang版更新以及所需的环境配置和第三方库。
摘要由CSDN通过智能技术生成

京东抢购

Python爬虫,自动登录京东网站,查询商品库存,价格,显示购物车详情等。
可以指定抢购商品,自动购买下单,然后手动去京东付款就行。

chang log

  • 2017-03-30 实现二维码扫码登陆

  • 2017-06-27 Golang版JD_AutoBuy

运行环境

Python 2.7

第三方库

  • Requests: 简单好用,功能强大的Http请求库

  • beautifulsoup4: HTML文档格式化及便签选择器

环境配置

pip install requests
pip install beautifulsoup4

 

 

项目源码分享

# -*- coding: utf-8 -*-
"""JD online shopping helper tool-----------------------------------------------------only support to login by QR code, username / password is not working now."""

import bs4import requests, requests.utils, pickleimport requests.packages.urllib3requests.packages.urllib3.disable_warnings()
import osimport timeimport jsonimport random

import argparse#from selenium import webdriver

import sysreload(sys)sys.setdefaultencoding('utf-8')
# get function nameFuncName = lambda n=0: sys._getframe(n + 1).f_code.co_name

def tags_val(tag, key='', index=0):    '''    return html tag list attribute @key @index    if @key is empty, return tag content    '''    if len(tag) == 0 or len(tag) <= index:        return ''    elif key:        txt = tag[index].get(key)        return txt.strip(' \t\r\n') if txt else ''    else:        txt = tag[index].text        return txt.strip(' \t\r\n') if txt else ''

def tag_val(tag, key=''):    '''    return html tag attribute @key    if @key is empty, return tag content    '''    if tag is None:         return ''    elif key:        txt = tag.get(key)        return txt.strip(' \t\r\n') if txt else ''    else:        txt = tag.text        return txt.strip(' \t\r\n') if txt else ''

class JDWrapper(object):    '''    This class used to simulate login JD    '''        def __init__(self, usr_name=None, usr_pwd=None):        # cookie info        self.trackid = ''        self.uuid = ''        self.eid = ''        self.fp = ''
        self.usr_name = usr_name        self.usr_pwd = usr_pwd
        self.interval = 0
        # init url related        self.home = 'https://passport.jd.com/new/login.aspx'        self.login = 'https://passport.jd.com/uc/loginService'        self.imag = 'https://authcode.jd.com/verify/image'        self.auth = 'https://passport.jd.com/uc/showAuthCode'                self.sess = requests.Session()
        self.headers = {
              'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36',            'ContentType': 'text/html; charset=utf-8',            'Accept-Encoding':'gzip, deflate, sdch',            'Accept-Language':'zh-CN,zh;q=0.8',            'Connection' : 'keep-alive',        }                self.cookies = {
  
        }
        '''        try:            self.browser = webdriver.PhantomJS('phantomjs.exe')        except Exception, e:            print 'Phantomjs initialize failed :', e            exit(1)        '''            @staticmethod    def print_json(resp_text):        '''        format the response content        '''        if resp_text[0] == '(':            resp_text = resp_text[1:-1]                for k,v in json.loads(resp_text).items():            print u'%s : %s' % (k, v)
    @staticmethod    def response_status(resp):        if resp.status_code != requests.codes.OK:            print 'Status: %u, Url: %s' % (resp.status_code, resp.url)            return False        return True
    def _need_auth_code(self, usr_name):        # check if need auth code        #         auth_dat = {
              'loginName': usr_name,        }        payload = {
              'r' : random.random(),            'version' : 2015        }                resp = self.sess.post(self.auth, data=auth_dat, params=payload)        if self.response_status(resp) :             js = json.loads(resp.text[1:-1])            return js['verifycode']
        print u'获取是否需要验证码失败'        return False
    def _get_auth_code(self, uuid):        # image save path        image_file = os.path.join(os.getcwd(), 'authcode.jfif')                    payload = {
              'a' : 1,            'acid' : uuid,            'uid' : uuid,            'yys' : str(int(time.time() * 1000)),        }                    # get auth code        r = self.sess.get(self.imag, params=payload)        if not self.response_status(r):            print u'获取验证码失败'            return False
        with open (image_file, 'wb') as f:            for chunk in r.iter_content(chunk_size=1024):                f.write(chunk)                                    f.close()                os.system('start ' + image_file)        return str(raw_input('Auth Code: '))
    def _login_once(self, login_data):        # url parameter        payload = {
              'r': random.random(),            'uuid' : login_data['uuid'],            'version' : 2015,        }                resp = self.sess.post(self.login, data=login_data, params=payload)        if self.response_status(resp):            js = json.loads(resp.text[1:-1])            #self.print_j
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
# JD_AutoBuy ## 京东抢购 Python爬虫自动登录京东网站,查询商品库存,价格,显示购物车详情等。 可以指定抢购商品自动购买下单,然后手动去京东付款就行。 ## chang log + 2017-03-30 实现二维码扫码登陆 ## 运行环境 Python 2.7 ## 第三方库 - [Requests][1]: 简单好用,功能强大的Http请求库 - [beautifulsoup4][2]: HTML文档格式化及便签选择器 ## 环境配置 ``` Python pip install requests pip install beautifulsoup4 ``` ## 使用帮助 ``` cmd > python scraper-jd.py -h usage: scraper-jd.py [-h] [-u USERNAME] [-p PASSWORD] [-g GOOD] [-c COUNT] [-w WAIT] [-f] [-s] Simulate to login Jing Dong, and buy sepecified good optional arguments: -h, --help show this help message and exit -u USERNAME, --username USERNAME Jing Dong login user name -p PASSWORD, --password PASSWORD Jing Dong login user password -g GOOD, --good GOOD Jing Dong good ID -c COUNT, --count COUNT The count to buy -w WAIT, --wait WAIT Flush time interval, unit MS -f, --flush Continue flash if good out of stock -s, --submit Submit the order to Jing Dong ``` ## 实例输出 ``` cmd +++++++++++++++++++++++++++++++++++++++++++++++++++++++ Thu Mar 30 17:10:01 2017 > 请打开京东手机客户端,准备扫码登陆: 201 : 二维码未扫描 ,请扫描二维码 201 : 二维码未扫描 ,请扫描二维码 201 : 二维码未扫描 ,请扫描二维码 201 : 二维码未扫描 ,请扫描二维码 202 : 请手机客户端确认登录 200 : BADACIFYhf6fakfHvjiYTlwGzSp4EjFATN3Xw1ePR1hITtw0 登陆成功 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ Thu Mar 30 17:10:28 2017 > 商品详情 编号:3133857 库存:现货 价格:6399.00 名称:Apple iPhone 7 Plus (A1661) 128G 黑色 移动联通电信4G手机 链接:http://cart.jd.com/gate.action?pid=3133857&pcount=1&ptype=1 商品已成功加入购物车! 购买数量:3133857 > 1 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ Thu Mar 30 17:10:30 2017 > 购物车明细 购买 数量 价格 总价 商品 Y 1 6399.00 6399.00 Apple iPhone 7 Plus (A1661) 128G 黑色 移动联通电信4G手机 总数: 1 总额: 6399.00 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ Thu Mar 30 17:10:30 2017 > 订单详情 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ ... ``` ## 注 代码仅供学习之用,京东网页不断变化,代
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值