目录
元素信息
-
get_attribute('class')
:- 作用:该方法用于获取网页元素的指定属性值,括号内为需要获取的属性名。在图中,示例获取的是元素的
class
属性。 - 使用方式:
element.get_attribute('class')
- 示例:如果网页元素是
<div class="content">
,调用get_attribute('class')
会返回"content"
。
- 作用:该方法用于获取网页元素的指定属性值,括号内为需要获取的属性名。在图中,示例获取的是元素的
-
.text
:- 作用:该属性用于获取网页元素中可见的文本内容。
- 使用方式:
element.text
- 示例:对于元素
<p>你好,世界</p>
,element.text
将返回"你好,世界"
。
-
.tag_name
:- 作用:该属性用于返回元素的标签名称。
- 使用方式:
element.tag_name
- 示例:对于元素
<button>点击我</button>
,element.tag_name
将返回"button"
。
示例
获取百度首页相关元素。
打印结果
完整代码
from selenium import webdriver
from selenium.webdriver.edge.service import Service
from selenium.webdriver.common.by import By
# 指定 msedgedriver.exe 的路径
path = 'D:\\software\\edge_driver\\msedgedriver.exe'
# 创建一个 Service 对象
service = Service(executable_path=path)
# 初始化浏览器对象
browser = webdriver.Edge(service=service)
# 打开网址
url = 'https://www.baidu.com'
browser.get(url)
input = browser.find_element(By.ID,'su')
# 获取标签的属性
print(input.get_attribute('class'))
# 获取标签的名字
print(input.tag_name)
# 获取元素文本
a = browser.find_element(By.LINK_TEXT,'新闻')
print(a.text)