【第二章 selenium基本操作之元素】

系列文章目录

第一章 【初识selenium自动化测试框架(详细记录)】



一、元素

1). F12进入开发调试工具(DevTools)
2). 选择图中红圈的箭头(select element),则鼠标放到相应元素上可看获取到信息,例如属性与内容等

或者右键点击某个元素,选择检查
在这里插入图片描述


二、选择元素

1 id

规范性的网站一般id是唯一的(在html中是标记该元素的)
本节使用的学习网址
在这里插入图片描述
代码如下
1)

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

# 创建 WebDriver 对象
wd = webdriver.Chrome()

# 调用WebDriver 对象的get方法 可以让浏览器打开指定网址
wd.get('https://www.byhy.net/_files/stock1.html')

# 根据id选择元素,返回的就是该元素对应的WebElement对象
element = wd.find_element(By.ID, 'kw')

# 通过该 WebElement对象,就可以对页面元素进行操作了
# 比如输入字符串到 这个 输入框里
element.send_keys('通讯\n')

2)
或者
basic_str 文件中

GUPIAO_URL= "https://www.byhy.net/_files/stock1.html"
GUPIAO_ID = "kw"
GUPIAO_SEARCH_BTN_ID = "go"

elementType 文件中

from selenium import webdriver
import basicStr as Str

wd = webdriver.Chrome()
wd.get('https://www.byhy.net/_files/stock1.html')

wd.find_element_by_id(Str.GUPIAO_ID).send_keys("通讯")
wd.find_element_by_id(Str.GUPIAO_SEARCH_BTN_ID).click()

wd.quit()

但是!

ps:Selenium 升级到版本 4 以后, 下面这种 find_element_by* 方法都作为过期不赞成的写法

wd.find_element(By.ID, 'username').send_keys('byhy')
wd.find_element(By.CLASS_NAME, 'password').send_keys('sdfsdf')
wd.find_element(By.TAG_NAME, 'input').send_keys('sdfsdf')
wd.find_element(By.CSS_SELECTOR,'button[type=submit]').click()

运行会有告警,应为如下

from selenium.webdriver.common.by import By

wd.find_element(By.ID, 'username').send_keys('byhy')
wd.find_element(By.CLASS_NAME, 'password').send_keys('sdfsdf')
wd.find_element(By.TAG_NAME, 'input'
  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值