通过WebElement接口获取值
size 获取元素的尺寸
text 获取元素的文本
get_attribute(name) 获取属性值
location 获取元素坐标,先找到要获取的元素,再调用该方法
page_source 返回页面源码
driver.title 返回页面标题
current_url 获取当前页面的URL
is_displayde() 判断该元素是否可见
is_enabled() 判断元素是否被使用
is_selected() 判断元素是否被选中
tag_name 返回元素的tagName
例子:百度首页的 新闻按钮
#! /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