WebElement接口获取值

通过WebElement接口获取值

  size  获取元素的尺寸

  text  获取元素的文本

  get_attribute(name)  获取属性值

  location  获取元素坐标,先找到要获取的元素,再调用该方法

  page_source  返回页面源码

  driver.title  返回页面标题

  current_url  获取当前页面的URL

  is_displayde()  判断该元素是否可见

  is_enabled()  判断元素是否被使用

  is_selected()  判断元素是否被选中

  tag_name  返回元素的tagName

例子:百度首页的 新闻按钮 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#! /usr/bin/env python
#coding=utf-8
 
from selenium import webdriver
import time
 
url = "https://www.baidu.com/"
driver = webdriver.Firefox()
driver.get(url)
time.sleep(3)
 
#size获取元素的尺寸
size = driver.find_element_by_id("kw").size
print("搜索框的尺寸:",size)
#搜索框的尺寸: {'height': 22, 'width': 500}
time.sleep(3)
 
#text获取元素的文本
news = driver.find_element_by_name("tj_trnews").text
print("新闻按钮的文本:",news)
#新闻按钮的文本: 新闻
time.sleep(3)
 
#get_attribute(name)获取属性值
href = driver.find_element_by_xpath(".//*[@id='u1']/a[1]").get_attribute("href")
name = driver.find_element_by_xpath(".//*[@id='u1']/a[1]").get_attribute("name")
print("新闻按钮的链接值:",href)
#新闻按钮的链接值: http://news.baidu.com/
print("新闻按钮的名字值:",name)
#新闻按钮的名字值: tj_trnews
time.sleep(3)
 
#location获取元素坐标,先找到要获取的元素,再调用该方法
location = driver.find_element_by_xpath(".//*[@id='u1']/a[1]").location
print("新闻按钮的坐标值:",location)
#新闻按钮的坐标值: {'x': 574, 'y': 19}
 
print("当前页面的URL:",driver.current_url)
#当前页面的URL: https://www.baidu.com/
 
print("当前页面的标题:",driver.title)
#当前页面的标题: 百度一下,你就知道
 
result1 = driver.find_element_by_xpath(".//*[@id='u1']/a[1]").is_displayed()
result2 = driver.find_element_by_name("tj_trnews").is_displayed()
print("新闻按钮是否可见1:",result1)
print("新闻按钮是否可见2:",result2)
#新闻按钮是否可见1: True
#新闻按钮是否可见2: True
 
driver.quit()

  结果:

新闻按钮的名字值: tj_trnews
新闻按钮的坐标值: {'x': 574, 'y': 19}
当前页面的URL: https://www.baidu.com/
当前页面的标题: 百度一下,你就知道
新闻按钮是否可见1: True
新闻按钮是否可见2: True

 

posted @   R-Bear  阅读(2866)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏
点击右上角即可分享
微信分享提示