Python,Selenium京东扫码登录保存cookie并爬取完整实例

Python,Selenium京东扫码登录cookie完整实例

前言

1.安装下载对应版本的selenium .

2.把解压缩的浏览器驱动edgedriver 放在python解释器所在的文件夹# 让selenium启动edge浏览器


提示:以下是本篇文章正文内容,下面案例可供参考

一、话不多说,直接上代码

代码如下(示例):

import time
import json
from selenium import webdriver
from selenium.webdriver.common.by import By
from lxml import etree
import pandas as pd
import os

# 如果不存在目录则创建
if not os.path.exists("./data"):
    os.makedirs("./data")

# 创建edge浏览器对象
op = webdriver.EdgeOptions()
op.add_experimental_option("detach", True)
op.add_experimental_option("detach", True)  # 防止闪退
op.add_argument("disable-blink-features=AutomationControlled")  # 防止被检测, 设置一个伪装与下面的execute_cdp_cmd同效果
web = webdriver.Edge(options=op)  # 实例化一个浏览器对象
web.maximize_window()
jd_domain = "https://www.jd.com/"
jd_login_url = 'https://passport.jd.com/new/login.aspx?/'


# 判断是否存在cookie,存在则添加到浏览器,不存在则登录获取保存cookie(避免每次都需要扫码)
def is_exists_cookies():
    cookie_file = './data/jd_cookies.txt'
    if os.path.exists(cookie_file):
        # 读取cookie文件中的内容
        web.get(jd_domain)  # 添加cookie前必须打开浏览器
        time.sleep(2)
        with open(cookie_file, 'r') as file:
            # 读取文中的cookies
            cookies = json.load(file)
            # 加载cookie信息
            for cookie in cookies:
                web.add_cookie(cookie)
        print("使用已保存的cookie登录")
    else:
        web.get(jd_login_url)
        # 等待用户登录并获取cookie,
        time.sleep(30)  # 第一次登录需要用户手动登录获取cookie(扫码登录等,需要时间长点)
        dictcookies = web.get_cookies()  # 登录成功后取出cookie,格式为字典
        jsoncookies = json.dumps(dictcookies)  # 字典转json
        with open(cookie_file, 'w') as f:
            f.write(jsoncookies)  # 写入cookie文件
        print("cookies已保存")


# 滚动条缓慢下滑
def slide(web):
    # 执行这段代码,会获取到当前窗口总高度
    js = "return action=document.body.scrollHeight"
    # 初始化现在滚动条所在高度为0
    height = 0
    # 当前窗口总高度
    new_height = web.execute_script(js)

    while height < new_height:
        # 将滚动条调整至页面底部
        for i in range(height, new_height, 400):
            web.execute_script('window.scrollTo(0, {})'.format(i))
            time.sleep(0.5)
        height = new_height
        time.sleep(2)
        new_height = web.execute_script(js)


# 获取页面数据
def get_product(web):
    slide(web)  # 缓慢滑动

    html_content = web.page_source
    et = etree.HTML(html_content)
    obj_list = et.xpath('//div[@class="gl-i-wrap"]')

    for item in obj_list:
        titles = item.xpath('./div[@class="p-name p-name-type-2"]/a/em/text()')
        # print(len(titles))
        title = ""
        for i in range(len(titles)):
            title = title + titles[i]
        title = title.strip().replace("\n", "").replace(" ", "")

        price_head = item.xpath('./div[@class="p-price"]/*/em/text()')[0]
        price_body = item.xpath('./div[@class="p-price"]/*/i/text()')[0]
        price = price_head + price_body

        shop_name = item.xpath('./div[@class="p-shop"]/span/a/text()')[0]

        sales1 = item.xpath('./div[@class="p-commit"]/strong/a/text()')[0]
        sales2 = item.xpath('./div[@class="p-commit"]/strong/text()')[0]
        sales = sales1 + sales2

        img = item.xpath('./div[@class="p-img"]/a/img/@src')[0]

        titless.append(title)
        saleses.append(sales)
        prices.append(price)
        shop_names.append(shop_name)
        urls.append(img)


# 开始爬取多页数据
def get_more(web, page):
    for i in range(3):
        print(f"爬取第{i}页数据")
        button = web.find_element(By.XPATH, '//*[@id="J_bottomPage"]/span[1]/a[9]')
        web.execute_script("arguments[0].click();", button)  # arguments[0]代表所传值element的第一个参数
        time.sleep(5)
        get_product(web)


def main():
    # 判断是否存在cookie,存在则添加到浏览器,不存在则登录获取保存cookie
    is_exists_cookies()
    web.refresh()  # 刷新网页
    time.sleep(2)
    # 发送请求并检索网页内容
    key = "小米14pro"
    search_url = f'https://search.jd.com/Search?keyword={key}'
    web.execute_script(f"window.open('{search_url}','_blank')")
    time.sleep(2)
    web.switch_to.window(web.window_handles[-1])  # 切换到最后一个标签页(新打开的页面)

    # 获取页面数据
    get_product(web)

    # 获取商品总页数
    page_num = web.find_element(By.XPATH, '//*[@id="J_bottomPage"]/span[2]/em[1]/b').text
    print(f"共计{page_num}页数据")

    # 开始爬取多页数据
    get_more(web, int(page_num) - 1)


if __name__ == '__main__':
	# 创建数据需要的空数组
    titless = []
    prices = []
    saleses = []
    urls = []
    shop_names = []
    main()

    data = {"标题": titless, '价格': prices, "店铺": shop_names, "销量": saleses, "图片": urls}
    pd.DataFrame(data).to_excel(f'./data/京东小米14pro销售.xlsx', index=False)

    print("全部完成")
    web.quit()

  • 13
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
# 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 > 订单详情 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ ... ``` ## 注 代码仅供学习之用,京东网页不断变化,代
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值