目录
前言
暑假学习了selenium(python网页库),写了京东商品秒杀的代码
本人目前小白入门,大佬勿喷!
一、selenium学习教程
这里推荐一个B站up主的教程,内容详细,适合小白:
https://www.bilibili.com/video/BV1Z4411o7TA?p=1
他家的一个学习网站:
http://www.byhy.net/tut/auto/selenium/01/
二、代码
from selenium import webdriver
import time,datetime
global driver
if __name__ == '__main__':
driver_path=r'C:\Users\万萌\AppData\Local\Google\Chrome\Application\chromedriver.exe'#这里是驱动存放路径,打开目标浏览器文件所在位置找到chromedriver.exe,将文件路径复制过来
driver=webdriver.Chrome(executable_path=driver_path)
driver.get("https://www.jd.com/")
driver.implicitly_wait(5)
loginin=driver.find_element_by_css_selector('.link-login')
loginin.click()
while True:#这里需要手机京东扫码登陆
if 'JD.COM' in driver.title:
break
else :
time.sleep(1)
driver.find_element_by_css_selector('[href="//cart.jd.com/cart.action"]').click()
for handle in driver.window_handles:
# 先切换到该窗口
driver.switch_to.window(handle)
# 得到该窗口的标题栏字符串,判断是不是我们要操作的那个窗口
if '购物车' in driver.title:
# 如果是,那么这时候WebDriver对象就是对应的该该窗口,正好,跳出循环,
break
driver.find_element_by_css_selector('.select-all').click()
driver.find_element_by_css_selector('.select-all').click()
time.sleep(2)
driver.find_element_by_xpath("/html/body/div[4]/div[1]/div[4]/div[2]/div/div[1]/div[1]/div/input").click()
buytime = '2021-08-27 20:00:00'#这里设置秒杀开始时间
while True:
nowtime=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
if '2021-08-27 20:00' in nowtime:#如果检测到当前时间字符串包含‘20:00’即立马提交订单
driver.find_element_by_xpath("/html/body/div[4]/div[1]/div[10]/div/div[2]/div/div/div/div[2]/div[2]/div/div[1]/a").click()
driver.find_element_by_xpath("/html/body/div[15]/div/div[11]/div[7]/div/div[2]/div[1]/button[1]").click()
print("OK!")
break
else:
driver.refresh()
driver.find_element_by_css_selector('.select-all').click()
driver.find_element_by_css_selector('.select-all').click()
driver.find_element_by_xpath("/html/body/div[4]/div[1]/div[4]/div[2]/div/div[1]/div[1]/div/input").click()
总结
目前成功率在40%左右,还有一些bug,希望与大家多多交流,共同学习进步,感谢!!!