You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python+Selenium获取指定image标签的属性文本?

使用Python Selenium获取SVG image标签的属性值
  • 先通过你已有的XPath定位到目标image元素
  • 调用get_attribute()方法获取对应属性的文本值

代码示例

from selenium import webdriver
from selenium.webdriver.common.by import By

# 初始化Chrome浏览器驱动
driver = webdriver.Chrome()
driver.get("你的网页URL")

# 定位SVG中的image元素
image_element = driver.find_element(By.XPATH, "//*[name()='g' and contains(@entityid, '61042482270050282')]/*[name()='image']")

# 获取目标属性值(替换成实际属性名,比如'xlink:href'、'src'或自定义属性名)
attribute_value = image_element.get_attribute("xlink:href")  # 示例用SVG常见的xlink:href,根据实际情况修改

# 如果属性值是路径格式(比如"/assets/down_state_16x16.png"),提取需要的文本部分
if attribute_value:
    target_text = attribute_value.split("/")[-1].split(".")[0]
    print(target_text)  # 输出: down_state_16x16
else:
    print("未找到目标属性或属性值为空")

# 关闭浏览器驱动
driver.quit()

关键说明

  • 若目标属性是SVG特有的命名空间属性(如xlink:href),直接传入完整属性名即可
  • 如果属性值本身就是down_state_16x16,无需额外分割,直接使用attribute_value即可
  • 若定位失败,需检查网页是否存在动态加载元素,必要时添加等待逻辑

内容的提问来源于stack exchange,提问作者mac

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 14:32:42