Selenium常用操作之单选复选框、下拉列表、键盘、截屏、断言、(显式隐式)等待

目录

1. 窗口最大化

2.单选框操作

3. 复选框操作

4. 下拉列表

5. selenium 三种等待

6. 键盘操作

7.截屏

8.断言

9. Selenium操作JS弹窗控件

10.鼠标悬停与释放


1. 窗口最大化

driver.maximize_window()

2.单选框操作

driver.find_element_by_xpath("//input[@value='berry']").click()

3. 复选框操作

berrCheckBox1 = driver.find_element_by_xpath('//input[@value="orange"]').click()

4. 下拉列表

driver.find_element_by_name("fruit").click()
time.sleep(2)
driver.find_element_by_id("watermelon").click()

5. selenium 三种等待

(1) 强制等待

  常用于调试

import time
time.sleep(2)

(2) 隐式等待

  简介:  

  a 、 driver.implicitly_wait(10),隐式等待设置了一个时间,在一段时间内网页是否加载完成,如果完成了,就进行下一步;在设置的时间内没有完成,则会报超时加载;

  b、缺点是不智能,因为随着ajax技术的广泛应用,页面的元素往往都可以局部加载,也就是在整个页面没有加载完成的时候,可能我们需要的元素已经加载完成,那就没有必要在等待整个页面的加载,执行下一步,而隐式等待满足不了这一点;
      另外一点,隐式等待的设置时全局性的,在开头设置过后,整个的程序运行过程中都会生效,都会等待页面加载完成,不需要每次都需要设置一遍。

<head>
    <meta charset="UTF-8">
    <title>你喜欢的水果</title>
    <script type="text/javascript">
    </script>
</head>
<body>
    <p id="p1">这是你爱吃的水果吗?</p>
    <br>
    <br>
    <a href="http://www.sogou.com" target="_blank">sogou 搜索</a>
</body>
from selenium import webdriver
import time
# 导入异常 ,
# NoSuchElementException:找不到页面元素的异常
# TimeoutException:时间异常,超过规定时间,抛出异常
from selenium.common.exceptions import NoSuchElementException,TimeoutException
# 异常的获取与处理
import traceback

driver = webdriver.Chrome()
url = "http://www.sogou.com"
driver.get(url)

# 设置隐式等待
driver.implicitly_wait(10)
# 浏览器最大化
driver.maximize_window()
try:
    searchBox = driver.find_element_by_id("query").send_keys("selenium")
    click = driver.find_element_by_id("stb").click()
except(NoSuchElementException,TimeoutException):
    traceback.print_exc()#获取异常

time.sleep(2)
driver.quit()

(3) 显式等待

  简介:

  selenium中的wait模块的WebDriverWait()方法,配合until或者until_not方法,在辅助一些判断条件,就可以构成这样一个场景:每经过多少秒就查看一次locator的元素是否可见,如果可见,就停止等待,如果不可见就继续等待直到超过规定的时间后,报超时异常;当然也可以判断某元素是否在规定时间内不可见等等的各种场景,需要根据自己实际的场景选择判断条件;

<head>
    <meta charset="UTF-8">
    <title>你喜欢的水果</title>
    <script type="text/javascript">
        function display_alert() {
            alert("I am an alert box !")
        }
    </script>
</head>
<input>
    <p>请选择你喜欢的水果</p>
    <select name="frult">
        <option id="peach" value="taozi">桃子</option>
        <option id="watermelon" value="西瓜">西瓜</option>
    </select>
    <br>
    <input type="button" onclick="display_alert()" value="Display alert box" />
    <input id="check" type="checkbox">是否喜欢吃水果?</input>
    <br><br>
    <input type="text" id="text" value="今年夏天西瓜很甜!">文本框</input>
</body>
from selenium import webdriver
import time
from selenium.common.exceptions import NoSuchElementException,TimeoutException
import  traceback
import os
#显式等待要用WebDriverWait
from selenium.webdriver.support.ui import WebDriverWait
#判断元素是否存在 expected_conditions  as EC:取别名
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
url = 'file:///'+os.path.abspath("test.html")
driver.get(url)

try:
    # 显示等待
    wait = WebDriverWait(driver,10,0.2) #浏览器驱动,10:代表最长超时时间(秒),0.2:间隔刷新时间(不写,0.5刷新一次)
    wait.until(EC.title_is("你喜欢的水果")) #判断标题是否等于 "你喜欢的水果"
    print(u"当前网页的标题是:'你喜欢的水果'") # u utf-8 编码

    #显示等待的另一种写法
    element = WebDriverWait(driver,10).until(lambda x:x.find_element_by_xpath("//input[@value='Display alert box']"))
    element.click()
    time.sleep(2)

    alert = wait.until(EC.alert_is_present())#判断有没有弹出 弹窗
    print(alert.text) #如果打开了,打印当前文本值
    time.sleep(2)
    alert.accept() #点击接受

except TimeoutException as e:
    print(traceback.print_exc())
except NoSuchElementException as e:
    print(traceback.print_exc())
except Exception as e:
    print(traceback.print_exc())

time.sleep(2)
driver.quit()

6. 键盘操作

(1) 获取并设置当前窗口位置

# 获取当前窗口的位置
posttion = driver.get_window_position()
print("初始值",posttion)

# 设置当前窗口位置
driver.set_window_position(x=120,y=120)
print("设置后",driver.get_window_position())

(2) 获取并设置当前窗口大小

# 设置当前窗口的大小
#设置新窗口大小,创建句柄,并取名为 'current'
driver.set_window_size(width="520",height="400",windowHandle='current')
print(driver.get_window_size(windowHandle='current'))

(3) 使用title属性识别和操作新弹出的浏览器窗口

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException,TimeoutException
# 导入期望场景类
from selenium.webdriver.support import expected_conditions as EC
# 导入BY类
from selenium.webdriver.common.by import By
#显式等待要用WebDriverWait
# 设置等待时间和超时时间
from selenium.webdriver.support.ui import WebDriverWait
# 导入堆栈类
import traceback
import time
# os.path子库以path为入口,用于操作和处理文件路径
import os

driver = webdriver.Chrome()
url= "file:///"+os.path.abspath("test.html")
driver.get(url)

# 显示等待找到页面上链接文字为“sougou搜索”的链接元素,找到后单击
# EC.element_to_be_clickable 判断是否被点击
WebDriverWait(driver,10,0.2).until(EC.element_to_be_clickable((By.LINK_TEXT,"sogou 搜索"))).click()

# 获取当前所有打开的浏览器窗口句柄
all_handles = driver.window_handles
# 打印当前浏览器窗口句柄
print(driver.current_window_handle)
# 打印打开的浏览器窗口的个数
print(len(all_handles))
time.sleep(2)

if len(all_handles)>0:
    try:
        for windouHandle in all_handles:
            # 切换窗口
            driver.switch_to.window(windouHandle)
            print(driver.title)
            #判断当前浏览器窗口的title窗口属性是否等于“搜狗搜索引擎 - 上网从搜狗开始”
            if driver.title == "搜狗搜索引擎 - 上网从搜狗开始":
                #显示等待页面搜索输入框加载完成,然后输入内容“sogou”首页的浏览器窗口被找到
                WebDriverWait(driver,10,0.2).until(lambda x:x.find_element_by_id("query")).send_keys("sogou首页的浏览器窗口被找到")
                time.sleep(2)
    except NoSuchElementException as e:
        print(traceback.print_exc())
    except TimeoutException  as e:
        print(traceback.print_exc())

#将浏览器窗口切换到默认窗口
driver.switch_to.window(all_handles[0])
#打印切换回默认窗口的title
print(driver.title)
#断言当前浏览器窗口的title属性是“你喜欢的水果”
assert  "你喜欢的水果" in driver.title
driver.quit()

(4)操作新弹出的浏览器窗口

<head>
    <meta charset="UTF-8">
    <title>你喜欢的水果</title>
    <script type="text/javascript">
    </script>
</head>
<body>
    <p id="p1">这是你爱吃的水果么</p>
    <br>
    <br>
    <a href="http://www.sogou.com" target="_blank">sogou 搜索</a>
</body>
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException,TimeoutException
# 导入期望场景类
from selenium.webdriver.support import expected_conditions as EC
# 导入BY类
from selenium.webdriver.common.by import By
#显式等待要用WebDriverWait
# 设置等待时间和超时时间
from selenium.webdriver.support.ui import WebDriverWait
# 导入堆栈类
import traceback
import time
# os.path子库以path为入口,用于操作和处理文件路径
import os

driver = webdriver.Chrome()
url= "file:///"+os.path.abspath("test.html")
driver.get(url)

# 显示等待找到页面上链接文字为“sougou搜索”的链接元素,找到后单击
# EC.element_to_be_clickable 判断是否被点击
WebDriverWait(driver,10,0.2).until(EC.element_to_be_clickable((By.LINK_TEXT,"sogou 搜索"))).click()

# 获取当前所有打开的浏览器窗口句柄
all_handles = driver.window_handles
# 打印当前浏览器窗口句柄
print(driver.current_window_handle)
# 打印打开的浏览器窗口的个数
print(len(all_handles))
time.sleep(2)

if len(all_handles)>0:
    try:
        for windouHandle in all_handles:
            # 切换窗口
            driver.switch_to.window(windouHandle)
            # elenium的page_source方法可以获取到页面源码
            PageSource = driver.page_source
            if "搜狗搜索" in PageSource:
                WebDriverWait(driver,10,0.2).until(lambda x:x.find_element_by_id("query")).send_keys("找到了")
                driver.find_element_by_id("stb").click()
                time.sleep(3)

    except NoSuchElementException as e:
        print(traceback.print_exc())
    except TimeoutException  as e:
        print(traceback.print_exc())

#将浏览器窗口切换到默认窗口
driver.switch_to.window(all_handles[0])
#打印切换回默认窗口的title
print(driver.title)

#断言当前浏览器窗口的title属性是“你喜欢的水果”
assert  "你喜欢的水果" in driver.title

driver.quit()

7.截屏

import time
from selenium import webdriver

driver = webdriver.Chrome()
url = "http://www.jg.com"
driver.get(url)
try:
    # 截屏
    result = driver.get_screenshot_as_file(r"d:\test.png")
    print(result)
except IOError as e:
    print(e)
driver.quit()

8.断言

# 通过断言页面是否存在某些关键字来确定页面而按照预期加载
assert "selenium" in driver.page_source,"页面源码中不存在该关键字!"

9. Selenium操作JS弹窗控件

(1)提示弹窗

<head>
    <meta charset="UTF-8">
    <title>弹窗控件</title>
    <script>
        function showPro() {
            var str=prompt('你快乐吗?')
            if (str){
                alert('谢谢你的回答!')
            }
        }
    </script>
    <script>
        function showAlert2() {
                alert('谢谢你的回答!')
        }
    </script>
     <script>
        function showAlert() {
                var x;
                x = confirm('确定要删除吗?');
                if (x ==true){
                    alert('点击了确认')
                }else{
                    alert('点击了取消')
                }
        }
    </script>
</head>
<body>
    <div align="center">
        <h4>你好,29快乐</h4>
        <input type="button" onclick="showPro()" value="输入框弹窗按钮"/>
        <input type="button" onclick="showAlert2()" value="提示弹窗按钮"/>
        <input type="button" onclick="showAlert()" value="确认弹窗按钮"/>
        <br><br><br>
        <span id="textSpan">
            <font style="color: green">还需要在努力呀</font>
        </span>
    </div>
</body>
from selenium import webdriver
import time
import os

driver = webdriver.Chrome()
driver.maximize_window()
url="file:///"+os.path.abspath("index.html")
driver.get(url)

# 获取alert对话框
driver.find_element_by_xpath("/html/body/div/input[2]").click()
alert = driver.switch_to.alert #获取弹窗的方法
time.sleep(2)
print(alert.text)#打印对话框文本
alert.accept()#接受弹窗
time.sleep(2)
driver.quit()

(2) 确认弹窗

from selenium import webdriver
import time
import os

driver = webdriver.Chrome()
driver.maximize_window()
url="file:///"+os.path.abspath("index.html")
driver.get(url)

# 获取alert对话框
driver.find_element_by_xpath("/html/body/div/input[3]").click()
alert = driver.switch_to.alert #获取弹窗的方法
time.sleep(2)
print(alert.text)#打印对话框文本
alert.accept()#接受弹窗
print(alert.text)#打印对话框文本
alert.accept()#接受弹窗
time.sleep(2)

driver.find_element_by_xpath("/html/body/div/input[3]").click()
alert = driver.switch_to.alert #获取弹窗的方法
time.sleep(2)
print(alert.text)#打印对话框文本
alert.dismiss() #选择 "取消按钮"
print(alert.text)#打印对话框文本
alert.accept()#接受弹窗

driver.quit()

(3)输入弹框

from selenium import webdriver
import time
import os

driver = webdriver.Chrome()
url = "file:///"+os.path.abspath("index.html")
driver.get(url)

# 获取prompt()输入对话框
driver.find_element_by_xpath("/html/body/div/input[1]").click()
# 获取警告对话框内的文本
prompt = driver.switch_to.alert
time.sleep(2)
# 打印取警告对话框内的文本
print(prompt.text)

# 在输入框内输入"努力"
prompt.send_keys("努力")
time.sleep(2)
# 点击确定按钮
prompt.accept()
# 获取警告框文本
prompt2 = driver.switch_to.alert
print(prompt2.text)

prompt2.dismiss()#取消按钮
driver.quit()

10.鼠标悬停与释放

鼠标释放

from selenium import webdriver
from selenium.webdriver import ActionChains
import time
import os

driver = webdriver.Chrome()
url="file:///"+os.path.abspath("mouse_test.html")
driver.get(url)

div = driver.find_element_by_id("div1")
# 在id属性值为'div1'的元素上,执行按下的鼠标左键,并保持
ActionChains(driver).click_and_hold(div).perform()
time.sleep(2)

# 释放按下的鼠标左键
ActionChains(driver).release(div).perform()

time.sleep(2)
driver.quit()

 鼠标悬停

from selenium import webdriver
#ActionChains 是自动化执行低级交互的一种方式,例如:鼠标移动,鼠标点按,键盘操作,文本操作等
from selenium.webdriver import ActionChains
import time
import os

driver = webdriver.Chrome()
url = "file:///"+os.path.abspath("test_001.html")
driver.get(url)

link1 = driver.find_element_by_link_text("鼠标指过来1")
link2 = driver.find_element_by_link_text("鼠标指过来2")
p= driver.find_element_by_xpath("//p")

ActionChains(driver).move_to_element(link1).perform()
time.sleep(2)
ActionChains(driver).move_to_element(p).perform()
time.sleep(2)
ActionChains(driver).move_to_element(link2).perform()
time.sleep(2)
ActionChains(driver).move_to_element(link1).perform()
time.sleep(2)

driver.quit()

以下是我收集到的比较好的学习教程资源,虽然不是什么很值钱的东西,如果你刚好需要,可以评论区,留言【777】直接拿走就好了

各位想获取资料的朋友请点赞 + 评论 + 收藏,三连!

三连之后我会在评论区挨个私信发给你们~

 

Supongo que te gusta

Origin blog.csdn.net/m0_70618214/article/details/132941750
Recomendado
Clasificación