selenium入门级项目 - 豆豆玩竞猜

2023-10-11 11:40

本文主要是介绍selenium入门级项目 - 豆豆玩竞猜,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

在初步学习selenium的定位方法之后,我们就可以找些网站来测试了,这次我选择的网站是豆豆玩

测试目的

  1. 点掉首页弹窗

在这里插入图片描述

  1. 模拟登陆,含简单的验证码识别
    在这里插入图片描述

  2. 表格提交
    在这里插入图片描述

  3. 获取15期结果,存进Mysql数据库

思路与主要代码

去JS弹窗

这个容易,获取CSS标签,点掉即可:

s = Service("C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe")
driver = webdriver.Chrome(options=chrome_options, service=s)
ddwURL = "http://www.doudouwan.net/"
driver.get(url=ddwURL)
time.sleep(6)
driver.find_elements(by=By.CLASS_NAME,value='layui-layer-btn0')[0].click()

模拟登陆

这里登陆填账号密码不再赘述,重点讨论验证码识别。

网站的验证码文件是html格式,并且是随机的,网页打开就会刷新一次:2578

我的思路是:网页截取验证码所在区域的图片,保存到本地,然后进行文字OCR识别,

我们不研究识别的原理,现在有很多开源的库可以供我们使用,选择了ddddocr,除了有广告,基本可以使用:

def validate(url):ocr = ddddocr.DdddOcr()with open(url, 'rb') as f:image = f.read()res = ocr.classification(image)return resdef snipScreent(url):driver.get(url)time.sleep(2)width = driver.execute_script("return document.documentElement.scrollWidth")height = driver.execute_script("return document.documentElement.scrollHeight")driver.set_window_size(width, height)  # 修改浏览器窗口大小# 搜索结果部分完整截图r_node = driver.find_element(by='xpath', value='/html/body/div[3]/div/div[2]/dl/dd[3]/img')print('网页模块尺寸:height={},width={}'.format(r_node.size['height'], r_node.size['width']))times = int(time.time())pngPath = r'D:\image\%s.png' % timesr_node.screenshot(pngPath)# im = Image.open(pngPath)# print("截图尺寸:height={},width={}".format(im.size[1], im.size[0]))return pngPathpicPath = snipScreent(url=ddwURL)
driver.find_element(by=By.CSS_SELECTOR,value="body > div.top > div > div.index_member.no_login > dl > dd.i.i_username > input").send_keys("bgone")
driver.find_element(by=By.CSS_SELECTOR,value="body > div.top > div > div.index_member.no_login > dl > dd.i.i_password > input").send_keys("123456")# downURL = "http://doudouwan.net/register/register_ver_code.html"
# picPath = download(url=downURL)
num = validate(url=picPath)
driver.find_element(by=By.CSS_SELECTOR,value="body > div.top > div > div.index_member.no_login > dl > dd.i.i_code > input").send_keys(num)
time.sleep(3)
driver.find_element(by=By.CSS_SELECTOR,value="body > div.top > div > div.index_member.no_login > dl > dd.a > a.submit").click()
randomIdle()

表格提交

投注本身也不难,但我们需要写一个算法以尽量维持程序运行:

Created with Raphaël 2.3.0 Start 初始投入100 等待结果 本局盈利d? 总共豆豆数 - 初始投入 * 2> 0? 初始投入 * 2 End yes no yes no
def throw():asserT = Falsewhile not asserT:try:t = driver.find_element(by=By.CSS_SELECTOR,value=r"body > div.fun_main > div.fun_left > div.left_table > table > tbody > tr:nth-child(6) > td:nth-child(1)").get_attribute("textContent")css = "#revoke_%s > a" % tdriver.find_element(by=By.CSS_SELECTOR, value=css).click()except Exception as ep:print(ep)randomIdle()driver.refresh()else:asserT = Truedef bet(input=0):a = getCoins()driver.find_element(by=By.CSS_SELECTOR, value="#tbLuck28Value1").send_keys(input)driver.find_element(by=By.CSS_SELECTOR, value="#tbLuck28Value3").send_keys(input)driver.find_element(by=By.CSS_SELECTOR, value="#tbLuck28Value5").send_keys(input)driver.find_element(by=By.CSS_SELECTOR, value="#tbLuck28Value7").send_keys(input)driver.find_element(by=By.CSS_SELECTOR, value="#tbLuck28Value9").send_keys(input)driver.find_element(by=By.XPATH, value="/html/body/div[3]/div[1]/div[5]/div/div[3]/div[2]/div/div[3]/a").click()return int(a)-5*inputdef getTimer():decrypt = driver.find_element(by=By.CSS_SELECTOR,value="#bettingLottTime").get_attribute("textContent")partake = driver.find_element(by=By.CSS_SELECTOR,value="#bettingOverTime").get_attribute("textContent")if "已停止参与" in partake:if "解谜中,请稍后" in decrypt:return Truereturn Falsep = False
while not p:initialC = 20mp = Falsefor i in range(1,maxloop):# time.sleep(50)driver.get(url=guessURL90)throw()# 投入a = bet(input=initialC)# 等待解谜timerAssert = getTimer()while not timerAssert:time.sleep(2)timerAssert = getTimer()time.sleep(5)## 获取结果driver.refresh()c = collection()print(c)if c < 0:initialC = initialC * 2if initialC*5 > (a+c):breaktime.sleep(5)elif c > 0:mp = Truebreak

数据库操作

先本地搭建mysql服务器,Navicat Premium 15 建个表ddw,字段为:
在这里插入图片描述
主键在Number上;然后脚本获取数据并存入:


class Sql():def __int__(self):self.host = "192.168.222.1"self.username = "root"self.password = ""def connectMysql(self):# 然后连接数据库connection = pymysql.connect(host="localhost",user="root",password="",db='ddw',charset='utf8mb4',cursorclass=pymysql.cursors.DictCursor)return connectiondef instertMysql(self,num,date,result,coin,hits,inn,out):connection = self.connectMysql()# 对数据库进行操作try:with connection.cursor() as cursor:# 创建新记录sql = "INSERT INTO `ddw`.`ddw` (`Number`, `DateTime`, `Result`, `Coins`, `Hits`, `In`, `Out`) VALUES (%s, %s, %s, %s, %s, %s, %s)"cursor.execute(sql, (num, date, result, coin, hits, inn, out))# 默认不会自动提交,所以需要我们自己提交来保存改变后的内容*connection.commit()with connection.cursor() as cursor:# 读取单个记录sql = "SELECT Number FROM ddw.ddw WHERE Number=%s"cursor.execute(sql, (num))result = cursor.fetchone()print(result)finally:connection.close()def selectMysql(self,index=0):# def instertMysql(self, mum, date, result, coin, hits, inn, out):# 对数据库进行操作try:with connection.cursor() as cursor:# 读取单个记录if not index:sql = "select * from ddw ORDER BY 'Number' DESC LIMIT 1"else:sql = "select * from ddw ORDER BY 'Number' DESC LIMIT %d"cursor.execute(sql, (index))result = cursor.fetchone()print(result)return resultfinally:connection.close()def collection():year = datetime.datetime.now().yearsql = Sql()connection = sql.connectMysql()content = driver.find_elements(by=By.XPATH,value="/html/body/div[3]/div[1]/div[5]/table/tbody/tr/td")alist = []for i in content:html = etree.fromstring(i.get_attribute("innerHTML"), parser=etree.HTMLParser())try:alist.append(html.xpath("//text()"))except Exception:alist.append([i.get_attribute("innerHTML")])usefulContent = alist[36:-1]#     0         1          2          3       4#  `Number`, `DateTime`, `Result`, `Coins`, `Hits`, `In`, `Out`for index in range(0,len(usefulContent),7):# import pdb# pdb.set_trace()# n = index % 7# if n == 0:Number= int(usefulContent[index][0])# elif n == 1:DateTime = str(year) + "-" + usefulContent[index+1][0]# elif n == 2:Result = int(usefulContent[index+2][0])# elif n == 3:Coins = "".join(usefulContent[index+3][0].split(","))# elif n == 4:Hits = int("".join(usefulContent[index+4][0].split(",")))# elif n == 5:In = int("".join(usefulContent[index+5][0].split(":")[-1].split(",")))Out = int("".join(usefulContent[index+5][1].split(":")[-1].split(",")))with connection.cursor() as cursor:try:existOne = "SELECT Number FROM ddw.ddw WHERE Number=%s"cursor.execute(existOne, (Number))result = cursor.fetchone()print(result)if not result:sql.instertMysql(Number, DateTime, Result, Coins, Hits, In, Out)except Exception as ep:print(ep)finally:cursor.close()connection.close()return In-Out

结果展示:
在这里插入图片描述

总结

难度系数低,可以获取数据用于日后数据分析

这篇关于selenium入门级项目 - 豆豆玩竞猜的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/187790

相关文章

springboot项目中整合高德地图的实践

《springboot项目中整合高德地图的实践》:本文主要介绍springboot项目中整合高德地图的实践,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一:高德开放平台的使用二:创建数据库(我是用的是mysql)三:Springboot所需的依赖(根据你的需求再

一文详解如何在idea中快速搭建一个Spring Boot项目

《一文详解如何在idea中快速搭建一个SpringBoot项目》IntelliJIDEA作为Java开发者的‌首选IDE‌,深度集成SpringBoot支持,可一键生成项目骨架、智能配置依赖,这篇文... 目录前言1、创建项目名称2、勾选需要的依赖3、在setting中检查maven4、编写数据源5、开启热

SpringBoot项目配置logback-spring.xml屏蔽特定路径的日志

《SpringBoot项目配置logback-spring.xml屏蔽特定路径的日志》在SpringBoot项目中,使用logback-spring.xml配置屏蔽特定路径的日志有两种常用方式,文中的... 目录方案一:基础配置(直接关闭目标路径日志)方案二:结合 Spring Profile 按环境屏蔽关

MySQL版本问题导致项目无法启动问题的解决方案

《MySQL版本问题导致项目无法启动问题的解决方案》本文记录了一次因MySQL版本不一致导致项目启动失败的经历,详细解析了连接错误的原因,并提供了两种解决方案:调整连接字符串禁用SSL或统一MySQL... 目录本地项目启动报错报错原因:解决方案第一个:第二种:容器启动mysql的坑两种修改时区的方法:本地

springboot项目中使用JOSN解析库的方法

《springboot项目中使用JOSN解析库的方法》JSON,全程是JavaScriptObjectNotation,是一种轻量级的数据交换格式,本文给大家介绍springboot项目中使用JOSN... 目录一、jsON解析简介二、Spring Boot项目中使用JSON解析1、pom.XML文件引入依

使用vscode搭建pywebview集成vue项目实践

《使用vscode搭建pywebview集成vue项目实践》:本文主要介绍使用vscode搭建pywebview集成vue项目实践,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录环境准备项目源码下载项目说明调试与生成可执行文件核心代码说明总结本节我们使用pythonpywebv

Maven项目中集成数据库文档生成工具的操作步骤

《Maven项目中集成数据库文档生成工具的操作步骤》在Maven项目中,可以通过集成数据库文档生成工具来自动生成数据库文档,本文为大家整理了使用screw-maven-plugin(推荐)的完... 目录1. 添加插件配置到 pom.XML2. 配置数据库信息3. 执行生成命令4. 高级配置选项5. 注意事

eclipse如何运行springboot项目

《eclipse如何运行springboot项目》:本文主要介绍eclipse如何运行springboot项目问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目js录当在eclipse启动spring boot项目时出现问题解决办法1.通过cmd命令行2.在ecl

SpringBoot项目Web拦截器使用的多种方式

《SpringBoot项目Web拦截器使用的多种方式》在SpringBoot应用中,Web拦截器(Interceptor)是一种用于在请求处理的不同阶段执行自定义逻辑的机制,下面给大家介绍Sprin... 目录一、实现 HandlerInterceptor 接口1、创建HandlerInterceptor实

Maven项目打包时添加本地Jar包的操作步骤

《Maven项目打包时添加本地Jar包的操作步骤》在Maven项目开发中,我们经常会遇到需要引入本地Jar包的场景,比如使用未发布到中央仓库的第三方库或者处理版本冲突的依赖项,本文将详细介绍如何通过M... 目录一、适用场景说明​二、核心操作命令​1. 命令格式解析​2. 实战案例演示​三、项目配置步骤​1