京东实现按时自动勾选购物车,结算
知识点属于python方面的web爬虫(web crawler),首先介绍一下selenium:
selenium主要是用来做自动化测试,支持多种浏览器,爬虫中主要用来解决JavaScript渲染问题。
模拟浏览器进行网页加载。
1
| from selenium import webdriver
|
本例采用谷歌浏览器进行测试:browser = webdriver.Chrome()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
| from selenium import webdriver import datetime import time
def login(): browser.get("https://www.jd.com") time.sleep(3) if browser.find_element_by_class_name("link-login"): browser.find_element_by_class_name("link-login").click() print("请在15秒内完成扫码") time.sleep(15) browser.get("https://cart.jd.com/cart.action") time.sleep(3)
now = datetime.datetime.now() print('login success:', now.strftime('%Y-%m-%d %H:%M:%S'))
def buy(times, choose): if choose == 2: print("请手动勾选需要购买的商品") while True: now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f') if now > times: if choose == 1: while True: try: if browser.find_element_by_name("toggle-checkboxes"): browser.find_element_by_name("toggle-checkboxes").click() break except Exception as e: print(e.args[0]) print("找不到购买按钮") while True: try: if browser.find_element_by_class_name("submit-btn"): browser.find_element_by_class_name("submit-btn").click() browser.find_element_by_id("order-submit").click() print("结算成功") break except: pass while True: try: if browser.find_element_by_id("order-submit"): browser.find_element_by_id("order-submit").click() now1 = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f') print("抢购成功时间:%s" % now1) except: pass print(now) time.sleep(0.01)
if __name__ == "__main__": times = input("请输入抢购时间,格式如(2020-02-21 20:00:00.000000):") browser = webdriver.Chrome() browser.maximize_window() login() choose = int(input("到时间自动勾选购物车请输入“1”,否则输入“2”:")) buy(times, choose)
|