京东 Python卫龙辣条

from bs4 import BeautifulSoup
import requests
import datetime
import time
import os
import random
import re
import json
import pickle


cookies = {}
headers = {}
sess = requests.Session()

def get_strtime_now():
    return datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
def login_by_QR():
    try:
        print('%s 请打开京东手机客户端,准备扫码登录' %(get_strtime_now()))
        url_login = 'https://passport.jd.com/new/login.aspx'

        # step1 open login page
        resp = sess.get(url_login)
        if resp.status_code != requests.codes.OK:
            print("%s 获取登录界面失败" %(get_strtimr_now()))
            return False
        ## save cookies
        for k, v in resp.cookies.items():
            cookies[k] = v
            
        # step2 get qr image
        url_show_qr = 'https://qr.m.jd.com/show'
        resp = sess.get(
            url_show_qr,
            cookies=cookies,
            params={
                'appid':133,
                'size':147,
                't':(time.time()*1000)
                }
            )
        if resp.status_code != requests.codes.OK:
            print('%s 获取二维码失败' %(get_strtime_now()))
            return False
        ## save cookies
        for k, v in resp.cookies.items():
            cookies[k] = v
        ## save qr code
        image_file = 'qr.png'
        with open(image_file, 'wb') as f:
            for chunk in resp.iter_content(chunk_size=1024):
                f.write(chunk)
        ## open qr code
        os.system('start '+image_file)

        #step3 check scan result
        url_check = 'https://qr.m.jd.com/check'
        retry_times = 100
        qr_ticket = None
        headers['Host'] = 'qr.m.jd.com'
        headers['Referer'] = 'https://passport.jd.com/new/login.aspx'
        while retry_times:
            retry_times -= 1
            resp = sess.get(
                url_check,
                headers = headers,
                cookies = cookies,
                params = {
                    'callback':'jQuery%u' % random.randint(1000000,9999999),
                    'appid': 133,
                    'token':cookies['wlfstk_smdl'],
                    '_':int((time.time()*1000))
                    }
                )
            if resp.status_code != requests.codes.OK:
                continue;
            js_data = json.loads(re.match(r'jQuery\d+\(([\s\S]+)\)', resp.text)[1])
            if js_data['code'] == 200:
                qr_ticket = js_data['ticket']
                break
            else:
                print('%s %s' %(get_strtime_now(), js_data['msg']))
            time.sleep(3)
        if not qr_ticket:
            print('%s 二维码登录失败' %(get_strtime_now()))
            return False

        #step4 validate scan result
        headers['Host'] = 'passport.jd.com'
        headers['Referer'] = 'https://passport.jd.com/uc/login?ltype=logout'
        url_ticket = 'https://passport.jd.com/uc/qrCodeTicketValidation'
        resp = sess.get(
            url_ticket,
            headers = headers,
            cookies = cookies,
            params = {
                't' : qr_ticket
                }
            )
        if resp.status_code != requests.codes.OK:
            print('%s 二维码登录校验失败' %(get_strtime_now()))
            return False
        #print(resp.text)
        #print(resp.headers)
        if not resp.headers.get('P3P'):
            if json.loads(resp.text).has_key('url'):
                print('%s 需要手动安全验证' %(get_strtime_now()))
                return False
            else:
                print('%s %s' %(get_strtime_now(), resp.text))
                return False
        ## login succeed
        headers['P3P'] = resp.headers['P3P']
        for k, v in resp.cookies.items():
            cookies[k] = v
        with open('cookie','wb') as f:
            pickle.dump(cookies, f)
        print('%s 登录成功' %(get_strtime_now()))
        return True
    except Exception as e:
        print('%s 异常 %s' %(get_strtime_now(), e))
        raise
    return False

def good_detail(stock_id, area_id=None):
    good_data = {
        'id' : stock_id,
        'name': '',
        'link': '',
        'price': '',
        'stock': '',
        'stockname': '',
        }
    try:
        stock_link = 'https://item.jd.com/{0}.html'.format(stock_id)
        resp = sess.get(stock_link)
        soup = BeautifulSoup(resp.text, 'html.parser')
        tags = soup.select('div#name h1')
        if len(tags) == 0:
            tags = soup.select('div.sku-name')
        good_data['name'] = re.match(r'.+\s+(.+)</div>',str(tags[0]))[1].strip(' ')
        print(good_data['name'])
    except Exception as e:
        print('Exp {0} : good_detail()'.format(e))
        
if __name__ == '__main__':
    stock_id = '29954742610'
    #login_by_QR()
    good_detail(stock_id)
    

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 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 > 订单详情 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ ... ``` ## 注 代码仅供学习之用,京东网页不断变化,代
好的,我会为您提供指导。 首先,您需要安装 Django 并创建一个新项目。在命令行中,输入以下命令: ``` django-admin startproject snacks ``` 这将创建一个名为 `snacks` 的新 Django 项目。 接下来,您需要创建三个应用程序。在命令行中,输入以下命令: ``` python manage.py startapp history python manage.py startapp images python manage.py startapp introduction ``` 这将创建三个名为 `history`、`images` 和 `introduction` 的新应用程序。 在您的项目中,您需要配置二级路由。在 `snacks` 目录下,打开 `urls.py` 文件,并添加以下代码: ```python from django.urls import include, path urlpatterns = [ path('', include('home.urls')), path('history/', include('history.urls')), path('images/', include('images.urls')), path('introduction/', include('introduction.urls')), ] ``` 这将为您的三个应用程序创建二级路由。 现在,您需要创建一个名为 `home` 的应用程序来处理您的主页。在命令行中,输入以下命令: ``` python manage.py startapp home ``` 在 `home` 应用程序的 `views.py` 文件中,您可以创建一个视图,该视图将呈现您的主页。例如: ```python from django.shortcuts import render def home(request): return render(request, 'home.html') ``` 在 `home` 应用程序的 `urls.py` 文件中,您可以创建一个 URL 模式,该模式将指向您的主页视图。例如: ```python from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), ] ``` 现在,您可以创建一个名为 `history` 的应用程序来处理您的食品历史。在 `history` 应用程序的 `views.py` 文件中,您可以创建一个视图,该视图将呈现您的食品历史。例如: ```python from django.shortcuts import render def history(request): return render(request, 'history.html') ``` 在 `history` 应用程序的 `urls.py` 文件中,您可以创建一个 URL 模式,该模式将指向您的食品历史视图。例如: ```python from django.urls import path from . import views urlpatterns = [ path('', views.history, name='history'), ] ``` 同样地,您可以创建一个名为 `images` 的应用程序来处理您的食品图片。在 `images` 应用程序的 `views.py` 文件中,您可以创建一个视图,该视图将呈现您的食品图片。例如: ```python from django.shortcuts import render def images(request): return render(request, 'images.html') ``` 在 `images` 应用程序的 `urls.py` 文件中,您可以创建一个 URL 模式,该模式将指向您的食品图片视图。例如: ```python from django.urls import path from . import views urlpatterns = [ path('', views.images, name='images'), ] ``` 最后,您可以创建一个名为 `introduction` 的应用程序来处理您的食品简介。在 `introduction` 应用程序的 `views.py` 文件中,您可以创建一个视图,该视图将呈现您的食品简介。例如: ```python from django.shortcuts import render def introduction(request): return render(request, 'introduction.html') ``` 在 `introduction` 应用程序的 `urls.py` 文件中,您可以创建一个 URL 模式,该模式将指向您的食品简介视图。例如: ```python from django.urls import path from . import views urlpatterns = [ path('', views.introduction, name='introduction'), ] ``` 现在,您可以在每个应用程序的 `templates` 文件夹中创建 HTML 模板,以呈现您的内容。例如,在 `home` 应用程序的 `templates` 文件夹中,您可以创建一个名为 `home.html` 的模板,以呈现您的主页内容。同样地,在 `history` 应用程序的 `templates` 文件夹中,您可以创建一个名为 `history.html` 的模板,以呈现您的食品历史内容。在 `images` 应用程序的 `templates` 文件夹中,您可以创建一个名为 `images.html` 的模板,以呈现您的食品图片内容。在 `introduction` 应用程序的 `templates` 文件夹中,您可以创建一个名为 `introduction.html` 的模板,以呈现您的食品简介内容。 最后,您可以使用 Django 的内置开发服务器来运行您的应用程序。在命令行中,输入以下命令: ``` python manage.py runserver ``` 这将启动服务器并让您在浏览器中查看您的网站。 希望这能帮助您开始制作您的零食网页!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值