selenium简单使用

本文详细介绍了使用Selenium进行网页元素定位、元素操作、键鼠操作、下拉框处理、弹出框管理和窗口操作的实战案例。涵盖了CSS选择器、XPath、ID、Name等多种定位方式,并演示了输入、点击、滑动、处理弹窗等常见操作。此外,还展示了在实际场景中如登录、搜索等任务的自动化流程。
摘要由CSDN通过智能技术生成

元素定位

from selenium import webdriver
import time

# 借助chromedriver打开浏览器
browser = webdriver.Chrome()
browser.get('file:///F:/%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD/p9/pagetest/%E6%B3%A8%E5%86%8CA.html')
# time.sleep(1)
# browser.find_element_by_id('userA').send_keys('hhh')
# time.sleep(1)
# browser.find_element_by_name('passwordA').send_keys('123')
# time.sleep(1)
# browser.find_element_by_id('telA').send_keys('12312345612')
# time.sleep(1)
# browser.find_element_by_partial_link_text('网站').click()

# xpath
# try:
#     browser.find_element_by_xpath('/html/body/div/fieldset/form/p[2]/input').send_keys('123')
#     browser.find_element_by_xpath('//form/p[3]/input').send_keys('123')
#     browser.find_element_by_xpath('//input[@placeholder="请输入电子邮箱"]').send_keys('123@qq.com')
#     browser.find_element_by_xpath('//input[@name="userA"] and [@class="login-test"]').send_keys('123@qq.com')
# except Exception as e:
#     raise e
# finally:
#     time.sleep(2)
#     browser.quit()

# # css
# # id选择器  #id名称
# browser.find_element_by_css_selector('#userA').send_keys('admin')
# # class选择器  .class名
# browser.find_element_by_css_selector('.emailA').send_keys('123@qq.com')
# # 元素选择器
# browser.find_element_by_css_selector('input').send_keys('admin')
# # 属性选择器(单属性)
# browser.find_element_by_css_selector("[name='user']").send_keys('admin')
# # 多属性
# browser.find_element_by_css_selector("[name='user']""[class='login-test']").send_keys('admin')
#
#
#
# # 层级选择器
# # 父子层级选择器
# browser.find_element_by_css_selector("#pa>#userA").send_keys('admin')
# # 隔代层级选择器
browser.find_element_by_css_selector(".zc #userA").send_keys('admin')
time.sleep(2)
browser.quit()


# if __name__ == '__main__':
#     main()

元素操作

from selenium import webdriver
import time
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()
driver.get("file:///F:/%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD/p9/pagetest/%E6%B3%A8%E5%86%8CA.html")

'''
获取元素信息:size,text,get_attribute
判断元素信息:id_displayed,is_enables,is_selected
'''


# 元素大小
# print(driver.find_element_by_xpath("//*[@placeholder='请输入用户名']").size)

# 元素的文本
# print(driver.find_element(By.PARTIAL_LINK_TEXT,'网站').text)

# 获取属性
# print(driver.find_element(By.PARTIAL_LINK_TEXT,'网站').get_attribute("id"))
# print(driver.find_element(By.PARTIAL_LINK_TEXT,'网站').get_property("id"))


# 判断页面的span标签是否可见
print("判断元素是否可见,默认应该是False:",driver.find_element(By.NAME,'sp1').is_displayed())
# # 判断页面中取消按钮是否可用
print("判断取消按钮是否可用,默认应该是False:",driver.find_element(By.ID,"cancelA").is_enabled())
# 可用的按钮(注册)
print("判断取消按钮是否可用,默认是True:",driver.find_element(By.TAG_NAME,'button').is_enabled())
# 判断页面中'旅游'对应的复选框是否为选择的状态
print("判断旅游复选框是否选中,默认应该是True:",driver.find_element(By.ID,"lyA").is_selected())
# 没有选中的
print("判断旅游复选框是否选中,默认应该是False:",driver.find_element(By.ID,'gwA').is_enabled())
driver.quit()

键鼠操作

from selenium import webdriver
import time
from selenium.webdriver.common.by import By
from selenium.webdriver import ActionChains
from selenium.webdriver.common.keys import Keys

driver = webdriver.Chrome()
driver.get("file:///F:/%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD/p9/pagetest/%E6%B3%A8%E5%86%8CA.html")
'''
鼠标操作的步骤:
1.生成鼠标对象:ActionChains
2.做对应的操作:
3.执行响应的操作:perform
'''
# 生成鼠标对象
action = ActionChains(driver)
# 右击
# action.context_click(driver.find_element(By.ID,"userA"))

# # 输入用户名,双击用户名
# element = driver.find_element(By.ID,"userA")
# element.send_keys("admin")
# time.sleep(3)
# # 双击
# action.double_click(element)
#
# # 悬停在注册上
# element = driver.find_element(By.CSS_SELECTOR,"button")
# # 悬停事件
# action.move_to_element(element)
#
# # 调用鼠标执行的方法
# action.perform()


'''
键盘操作:
1.send_keys(Keys.BACK_SPACE)  删除(BackSpace)
2.send_keys(Keys.SPACE)       空格(Space)
3.send_keys(Keys.TAB)         制表(TAB)
4.send_keys(Keys.ESCAPE)      回退(ESCAPE)
5.send_keys(Keys.ENTER)       回车(ENTER)
6.send_keys(Keys.CONTROL,'a') 全选(ctrl+a)
7.send_keys(Keys.CONTROL,'c') 全选(ctrl+c)
8.send_keys(Keys.CONTROL,'v') 全选(ctrl+v)

'''
# 1.输入用户名:admin1,暂停2秒,删除‘1’
element = driver.find_element(By.ID,'userA')
element.send_keys("admin1")
time.sleep(2)
element.send_keys(Keys.BACK_SPACE)
# 删除最后一个字符串  clear()

# 2.全选用户名:admin,暂停2秒
element.send_keys(Keys.CONTROL,"a")
time.sleep(2)
# 3.复制用户名:admin,暂停两秒
b = element.send_keys(Keys.CONTROL,'c')
# 4.粘贴到密码框
driver.find_element(By.ID,"passwordA").send_keys(Keys.CONTROL,'v')
time.sleep(2)
driver.quit()

下拉框

import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select


driver = webdriver.Chrome()
driver.maximize_window()
# 打开测试网站
driver.get("file:///F:/%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD/p9/pagetest/%E6%B3%A8%E5%86%8CA.html")

element = driver.find_element(By.CSS_SELECTOR,"#selectA")

# 创建下拉框对象
select = Select(element)

# 通过select对象的index来选择广州
time.sleep(2)
select.select_by_index(2)

# 通过select对象的value来选择上海
time.sleep(2)
select.select_by_value("sh")

# 通过select对象的visible来选择深圳
time.sleep(2)
select.select_by_value("深圳")

# 退出
time.sleep(3)
driver.quit()


弹出框

import time
from selenium import webdriver
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()
driver.maximize_window()

'''
alert.text 获取弹出框提示信息
alert.accept()确定弹出框
alert.dismiss()取消弹出框
'''

# 打开测试网站
driver.get("file:///F:/%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD/p9/pagetest/%E6%B3%A8%E5%86%8CA.html")
# 点击alert按钮
driver.find_element(By.ID, 'alerta').click()
time.sleep(3)
# 处理弹出框
# 获取弹出框
alert = driver.switch_to.alert

# 打印信息,然后取消
print(alert.text)
alert.dismiss()

# 在用户输入框中输入admin
driver.find_element(By.ID, 'userA').send_keys('admin')
# 退出
time.sleep(3)
driver.quit()

弹出框

import time
from selenium import webdriver

driver = webdriver.Chrome()
driver.maximize_window()

# 打开测试网站
driver.get("file:///F:/%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD/p9/pagetest/%E6%B3%A8%E5%86%8CA.html")
time.sleep(3)

# 自定义js
js = "window.scrollTo(0,2000)"

# 执行js
driver.execute_script(js)

# 等待3s
time.sleep(3)

# 退出浏览器驱动
driver.quit()

窗口操作

import time
from selenium import webdriver
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()
driver.maximize_window()

# # 打开测试网站
# driver.get("file:///F:/%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD/p9/pagetest/%E6%B3%A8%E5%86%8C%E5%AE%9E%E4%BE%8B.html")
# driver.implicitly_wait(10)
#
# # 针对主页的用户输入admin
# driver.find_element(By.ID, "userA").send_keys("admin")
# time.sleep(2)
#
# #   针对注册用户a输入admin
# driver.switch_to.frame(driver.find_element(By.ID, 'idframe1'))
# driver.find_element(By.ID, "AuserA").send_keys("adminA")
# time.sleep(2)
#
# # 回到默认页面
# driver.switch_to.default_content()
# time.sleep(2)
#
# # 针对注册用户B输入用户名adminB
# ele_frame = driver.find_element(By.ID, 'ZCA')
# driver.switch_to.frame(ele_frame)
# driver.find_element(By.ID, "BuserA").send_keys("adminB")
#
# time.sleep(2)
# driver.quit()

'''
获取当前窗口句柄:driver.current_window_handle
获取所有窗口句柄:driver.window_handles
切换窗口句柄:driver.switch_to.window(window_handle)
窗口句柄:由操作系统组成的一串唯一的识别码,是一串字符
'''

driver.implicitly_wait(10)


driver.get("file:///F:/%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD/p9/web%E8%87%AA%E5%8A%A8%E5%8C%96/pagetest/%E6%B3%A8%E5%86%8C%E5%AE%9E%E4%BE%8B.html")


# 在注册实例页面中点击 注册A页面
time.sleep(1)

driver.find_element(By.ID,"idfr").click()
time.sleep(1)
# 获取当前窗口句柄信息
print(driver.current_window_handle)

# 获取当前窗口句柄
windows = driver.window_handles

# 切换窗口句柄
driver.switch_to.window(windows[-1])
# z在注册A页面中输入用户名和密码
driver.find_element(By.ID,'userA').send_keys('admin')

time.sleep(2)
driver.quit()




'''
目的:当程序运行出错时,通过截图文件能够更直观的知道具体是那个操作步骤出现了找错误
窗口截图就是吧出错的图片保存到指定位置
截图方法:driver.get_screenshot_as_file(filename)
        截图的文件名必须是以png结尾
        filename中的文件目录必须手动创建
'''

# driver.maximize_window()
#
# driver.get("file:///F:/%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD/p9/web%E8%87%AA%E5%8A%A8%E5%8C%96/pagetest/%E6%B3%A8%E5%86%8C%E5%AE%9E%E4%BE%8B.html")
#
# try:
#     #输入用户名
#     driver.find_element(By.ID,'userA').send_keys('admin')
#     #输入密码
#     driver.find_element(By.ID,'padd').send_keys('12345')
# except Exception as e:
#     name = '../img/'+str(time.time())+'error.png'
#     print(name)
#     driver.get_screenshot_as_file(name)
#
# finally:
#     time.sleep(3)
#     driver.quit()

小案例

from selenium import webdriver
from selenium.webdriver.common.by import By
import time
from selenium.webdriver.support.wait import WebDriverWait

driver = webdriver.Chrome()
driver.maximize_window()

# 进入首页
driver.get("https://www.szlcsc.com/")
# element = WebDriverWait(driver,10,1,lambda x:x.find_elemet(By.XPATH,"//div[@class='reg']/a[2]"))
# element.click()
# 进入登录页面
driver.find_element(By.XPATH, "//div[@class='reg']/a[2]").click()
# 切换账号密码登陆
driver.find_element(By.XPATH, "//div[@class='login_beij_top']/div[2]/span").click()
# 输入账号密码
driver.find_element(By.XPATH, "//input[@placeholder='客户编号/手机号码/邮箱']").send_keys('15040215866')
driver.find_element(By.XPATH, "//input[@placeholder='请输入密码']").send_keys('qwe55555aaa')
# 登录
driver.find_element(By.XPATH, "//div[@class='x_land2']/input[@type='button']").click()
# 搜索框
driver.find_element(By.XPATH, "//input[@class='sch-bd02']").send_keys('二极管')
# 搜索
driver.find_element(By.XPATH, "//input[@class='sch-bd03']").click()
time.sleep(2)
# 点击提示
# know_btn = driver.find_element_by_class_name('ok')
know_btn = driver.find_element(By.XPATH,"//button[@class='ok']")

if know_btn:
    know_btn.click()
else:
    pass

# 滑动

driver.execute_script("window.scrollTo(0,2000)")
time.sleep(2)
driver.execute_script("window.scrollTo(2000,0)")
time.sleep(2)


# 加入购物车
driver.find_element(By.XPATH, "//table[1]/tbody/tr/td/ul/li/button[1]").click()
time.sleep(2)
# 点击购物车图标
driver.find_element(By.XPATH, "//span[@class='cart-icon-a']/span[@class='cart-icon']").click()
time.sleep(2)
# 点击知道了
# know_btn  = driver.find_element_by_class_name('ok')
new_btn  = driver.find_element(By.XPATH,"//div[@class='guide-box-1']/button")
# //div[@class='guide-box-1']

if new_btn:
    know_btn.click()
    time.sleep(2)
else:
    pass
new_btn2 = driver.find_element(By.XPATH,"//div[@class='guide-box-2']/button")
if new_btn2:
    new_btn2.click()
    time.sleep(2)
else:
    pass
# 截图
img_name = '../img/' + str(time.time()) + '.png'
driver.get_screenshot_as_file(img_name)
time.sleep(2)
driver.quit()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

(initial)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值