从0开始python学习-21.selenium 元素的常见操作

复制代码
1. 输入内容:send_keys()
2. 点击(鼠标的左击):click()
3. 清除文本:clear()
4. 提交表单:submit()
5. 获取元素的大小:size  如果没有文本内容那么是空值
6. 获取元素的文本信息:text
7. 获取元素的属性:get_attribute()
8. 判断元素是否可见:is_display() 返回True/False
9. 判断元素是否可用:is_enable() 返回True/False
10.截图:get_screenshot_as_file() 或 save_screenshot()
python 复制代码
from time import sleep
from selenium import webdriver
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()

url = "https://www.baidu.com/"

driver.get(url)

driver.maximize_window ()

# 输入框:<input id="kw" name="wd" class="s_ipt" value="" maxlength="255" autocomplete="off">
# 百度一下:<input type="submit" id="su" value="百度一下" class="bg s_btn">
# 输入内容:send_keys()
driver.find_element(By.ID, 'kw').send_keys('1111')
sleep(3)

# 点击(鼠标的左击):click()
driver.find_element(By.ID, 'su').click()
sleep(5)

# 清除文本:clear()
driver.find_element(By.ID, 'kw').clear()
sleep(3)

# 提交表单:submit()
driver.find_element(By.ID, 'kw').send_keys('2222')
driver.find_element(By.ID, 'kw').submit()
sleep(10)

# <a href="http://news.baidu.com" target="_blank" class="mnav c-font-normal c-color-t">新闻</a>
# xpath: //*[@id="s-top-left"]/a[1]

# 获取元素的大小:size
print(driver.find_element(By.XPATH, '//*[@id="s-top-left"]/a[1]').size)  # {'height': 23, 'width': 26}

# 获取元素的文本信息:text
print(driver.find_element(By.XPATH, '//*[@id="s-top-left"]/a[1]').text)  # 新闻

# 获取元素的内容/属性:get_attribute()
print(driver.find_element(By.XPATH, '//*[@id="s-top-left"]/a[1]').get_attribute('innerText'))  # 新闻
print(driver.find_element(By.XPATH, '//*[@id="s-top-left"]/a[1]').get_attribute('class'))  # mnav c-font-normal c-color-t

# 判断元素是否可见:is_display()
print(driver.find_element(By.XPATH, '//*[@id="s-top-left"]/a[1]').is_displayed())  # True

# 判断元素是否可用:is_enable()
print(driver.find_element(By.XPATH, '//*[@id="s-top-left"]/a[1]').is_enabled())  # True

# 截图:get_screenshot_as_file() 或 save_screenshot()
driver.get_screenshot_as_file('./1png')
driver.save_screenshot('./2.jpg')
sleep(2)

driver.quit()
相关推荐
Dmz丶29 分钟前
前端转 AI 100 天 Day 44:前端集成实战——用 React 给 Agent 做个正式界面
python
jay神37 分钟前
基于 YOLOv8 的手势识别系统(Web 版)
前端·人工智能·python·深度学习·yolo·计算机视觉·计算机毕业设计
DeepVisionary1 小时前
阿里云上线旗舰多模态新模型,不公布跑分且限时14天退役
python·自动化
东莞市云毅网络有限公司1 小时前
FAQ 覆盖度打分:TF-IDF 与向量嵌入双路召回的 Python 实现
python·数据清洗·rag·企业知识库·文档解析
爱笑的k111 小时前
nano-vllm 源码剖析:千行 Python 手写离线推理引擎的调度、显存与并行时序
开发语言·python·vllm
用户8356290780512 小时前
使用 Python 控制 Excel 工作表的分页位置
后端·python
用户8356290780512 小时前
Python 如何在 Word 中添加和管理文档变量
后端·python
X1A0RAN2 小时前
PPT 图片批量处理教程:导出全部幻灯片 · 提取全部素材
开发语言·javascript·powerpoint
熊猫钓鱼>_>3 小时前
普通用户视角的端侧智能体验手记【鸿蒙心迹】
开发语言·人工智能·华为·智能手机·性能优化·ai编程·harmonyos
瑞雪兆丰年兮3 小时前
JavaWeb-day13-SpringBootWeb事务管理&AOP
java·开发语言·springboot·javaweb·事务·web·aop