Python使用Selenium实现网页自动化之元素定位与操作

📅 2026/8/2 2:31:49
Python使用Selenium实现网页自动化之元素定位与操作
获取元素属性找到元素只是第一步,更重要的是获取元素的信息。比如图片的链接、按钮的文字、输入框的值等等。1. 获取属性值以百度首页的 logo 为例,看看怎么获取它的图片地址:img hidefocus="true" 代码示例:import time from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.by import By s = Service(r'D:\driver\chromedriver.exe') browser = webdriver.Chrome(service=s) browser.get(r'https://www.baidu.com/') time.sleep(2) # 定位百度 logo logo = browser.find_element(By.CLASS_NAME, 'index-logo-src') # 打印元素对象本身 print(f"元素对象: {logo}") # 获取 src 属性(图片地址) logo_url = logo.get_attribute('src') print(f"Logo 地址: {logo_url}") # 还可以获取其他属性 print(f"宽度: {logo.get_attribute('width')}") print(f"高度: {logo.get_attribute('height')}") browser.quit()输出结果:元素对象: selenium.webdriver.remote.webelement.WebElement ... Logo 地址: https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png 宽度: 270 高度: 129常用场景:爬取图片时获取src属性获取链接的href属性获取输入框的value属性(用户输入的内容)2. 获取文本内容获取元素显示的文本,用.text属性:以百度热榜为例:a span1/span span北京冬奥闭幕 2026米兰见/span /a代码示例:import time from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.by import By s = Service(r'D:\driver\chromedriver.exe') browser = webdriver.Chrome(service=s) browser.get(r'https://www.baidu.com/') time.sleep(2) # 定位热榜第一条 hot = browser.find_element(By.CSS_SELECTOR, '#hotsearch-content-wrapper li:nth-child(1) a') # 获取显示的文本 print(f"热榜标题: {hot.text}") # 获取链接地址 print(f"链接地址: {hot.get_attribute('href')}") browser.quit()输出结果:热榜标题: 1北京冬奥闭幕 2026米兰见 链接地址: https://www.baidu.com/s?cl=3tn=baidutop10...注意:.text获取的是元素显示在页面上的文字,不是 HTML 里的属性。3. 获取其他属性元素还有很多有用的属性可以获取:import time from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.by import By s = Service(r'D:\driver\chromedriver.exe') browser = webdriver.Chrome(service=s) browser.get(r'https://www.baidu.com/') time.sleep(2) logo = browser.find_element(By.CLASS_NAME, 'index-logo-src') # 获取元素 id(Selenium 内部标识,不是 HTML 的 id) print(f"元素 ID: {logo.id}") # 获取元素在页面上的位置(坐标) print(f"位置坐标: {logo.location}") # 获取元素的标签名 print(f"标签名: {logo.tag_name}") # 获取元素的尺寸 print(f"尺寸大小: {logo.size}") browser.quit()输出结果:元素 ID: ffec5900-4bd5-4162-a127-e970bc3e85a6 位置坐标: {'x': 490, 'y': 151} 标签名: img 尺寸大小: {'height': 129, 'width': 270}这些属性有什么用?location- 做截图时确定元素位置size- 判断元素是否可见(大小为0可能是隐藏的)tag_name- 确认元素类型页面交互操作页面交互就是模拟用户的各种操作:输入文字、点击按钮、选择下拉框等等。1. 输入文本使用send_keys()方法在输入框中输入文字:import time from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.by import By s = Service(r'D:\driver\chromedriver.exe') browser = webdriver.Chrome(service=s) browser.get(r'https://www.baidu.com/') time.sleep(2) # 在搜索框输入"python" browser.find_element(By.CLASS_NAME, 's_ipt').send_keys('python') print("已输入: python") time.sleep(2) browser.quit()注意:send_keys()会在原有内容后面追加如果要替换内容,先调用clear()