6

selenium入门详细指南(附淘宝抢购案例)

 3 years ago
source link: https://zhuanlan.zhihu.com/p/259626718
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

selenium入门详细指南(附淘宝抢购案例)

公号:python大数据分析

selenium是一款web自动化测试工具,可以很方便地模拟真实用户对浏览器进行操作,它支持各种主流浏览器:IE、Chrome、Firefox、Safari、Opera等。

v2-0b32476f15f5181588eecc2b25cbc41f_720w.jpg

selenium有多种编程语言的客户端驱动,编写自动化脚本语法简洁,其中python的selenium库便非常的受欢迎。

你可以使用selenium做web测试或者爬虫,自动抢票、自动下单也可以用selenium来做。

演示自动打开淘宝网(文末会有秒抢流程):

v2-3203a134a21217e5a6d13bab1620a359_b.jpg

使用Selenium实现自动化测试,需要3个要素:

1.selenium客户端或者与特定编程语言绑定的客户端驱动,可以是python,java,js等;

2.浏览器驱动, 这个驱动是根据不同的浏览器开发的,不同的浏览器使用不同的webdriver驱动程序且需要对应相应的浏览器版本;

3.浏览器,目前selenium支持市面上大多数浏览器,如:火狐,IE等;

安装selenium

可以使用pip或conda命令安装selenium:

pip install selenium

安装浏览器驱动

Selenium调用浏览器必须有一个webdriver驱动文件,下载好后把驱动程序放到python安装目录里即可。

各大浏览器驱动下载地址:
Firefox: https://github.com/mozilla/geckodriver/releases/

Chrome: https://sites.google.com/a/chromium.org/chromedriver/

IE: http://selenium-release.storage.googleapis.com/index.html

以Chrome为例:

先在设置里查看Chrome版本:

然后下载对应的chromedrive,可以在淘宝的镜像网站下载: http://npm.taobao.org/mirrors/chromedriver/

找到对应的版本号下载,解压到python安装目录里,或者anaconda安装目录scripts文件夹里。



selenium操作浏览器

在notebook中进行selenium的脚本编写,可以随写随调,非常方便。

首先需要从selenium中导入webdriver模块:

from selenium import webdriver

然后打开浏览器:

browser = webdriver.Chrome()

最后可以打开某网址:

browser.get("https://www.taobao.com/")

针对浏览器的主要操作方法:

  • 创建浏览器对象:driver = http://webdriver.xxx()
  • 窗口最大化:maximize_window()
  • 获取浏览器尺寸:get_window_size()
  • 设置浏览器尺寸:set_window_size()
  • 获取浏览器位置:get_window_position()
  • 设置浏览器位置:set_window_position(x,y)
  • 关闭当前标签/窗口:close()
  • 关闭所有标签/窗口:quit()

selenium定位元素

因为selenium是模仿真实点击浏览器的行为,所以必须要先定位网页元素,才能进行各种操作。

「定位页面元素的8种主要方式」

  • id定位:driver.find_element_by_id(value)
  • name属性值定位:driver.find_element_by_name(value)
  • 类名定位: driver.find_element_by_class_name(value)
  • 标签名定位: driver.find_element_by_tag_name(value)
  • 链接文本定位:driver.find_element_by_link_text(value)
  • 部分链接文本:driver.find_element_by_partial_link_text(value)
  • xpath路径表达式:driver.find_element_by_xpath(value)
  • css选择器:driver.find_element_by_css_selector(value)

selenium操作网页

定位元素后,需要对网页进行各种操作,比如点击、刷新、保存等。

点击展开新的页面,点击方法:element.click()

其他主要操作方法:

  • 请求某个url:driver.get(url)
  • 刷新页面操作:refresh()
  • 回退到之前的页面:back()
  • 前进到之后的页面:forward()
  • 获取当前访问页面url:current_url
  • 获取当前浏览器标题:title
  • 保存图片:get_screenshot_as_png()/get_screenshot_as_file(file)
  • 网页源码:page_source

使用selenium抢购商品(只供学习,不保证效果)

  1. 导入selenium相关模块
# 导入库
from selenium import webdriver
import datetime
import time打开chrome浏览器
# 记录时间
now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
# 打开chrome 
browser = webdriver.Chrome()

2. 登录淘宝

# 登录
def login():
    # 打开淘宝首页,通过扫码登录
    browser.get("https://www.taobao.com/")
    time.sleep(3)
    # 打开登录界面
    find_login = browser.find_element_by_link_text("亲,请登录")
    if find_login:
        find_login.click()
        print("请扫码登录")
        time.sleep(10)
        
login()

3. 选择购物车列表

# 选择购物车列表
def picking(method):
    # 是否全选购物车
    if method == 0:
        while True:
            try:
                if browser.find_element_by_id("J_SelectAll1"):
                    browser.find_element_by_id("J_SelectAll1").click()
                    print('全选购物车成功')
                    break
            except:
                print(f"找不到购买按钮")
    else:
        print(f"请手动勾选需要购买的商品")
        time.sleep(1)

4. 点击结算按钮

# 点击结算按钮
def settlement():
    while True:
        try:
            if browser.find_element_by_id('J_SelectedItemsCount').text >= '1':
                browser.find_element_by_link_text("结 算").click()
                print(f"结算成功,准备提交订单")
                break
        except:
            pass

5. 点击提交订单按钮

# 点击提交订单按钮
def submitting():
    while True:
        try:
            if browser.find_element_by_link_text('提交订单'):
                browser.find_element_by_link_text('提交订单').click()
                print(f"抢购成功,请尽快付款")
                break
        except:
            print(f"再次尝试提交订单")

6. 开始执行抢购

def run(times):
    # 打开购物车列表页面
    print('正在抢购!')
    browser.get("https://cart.taobao.com/cart.htm")
    time.sleep(3)
    while True:
        now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
        # 对比时间,时间到的话就点击结算
        if now > times:
            # 全选购物车
            picking(0)
            # 点击结算按钮
            settlement()
            # 提交订单
            submitting()
            print(now)
            break

结论

selenium还有很多强大的功能,后续会继续分享,也期待大家留言说说你的selenium使用心得。

最后补充一句,因为selenium涉及操作网页,所以需要使用者有一定的html知识储备,大家学之前可以先去看看html基础知识。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK