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

如何用Python提取HTML标签的Class属性值?支持Selenium/BeautifulSoup

当然可以!既然你的脚本已经基于Selenium开发,其实有两种简单靠谱的方式来提取这个动态变化的class属性值——要么直接用Selenium本身的API,要么结合BeautifulSoup来解析页面源码,两种都能完美适配你的需求。

方法1:直接用Selenium提取

因为Selenium本身就支持元素属性的获取,核心思路是先通过其他稳定的属性定位到目标img元素(毕竟class是动态变化的,不能用它来定位),然后提取它的class值。

比如你示例里的img有固定的alt="SOME TEXT",就可以用这个来定位:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
driver.get("你的目标页面URL")

# 用显式等待确保元素加载完成(避免页面加载慢导致找不到元素)
target_img = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.XPATH, "//img[@alt='SOME TEXT']"))
)

# 提取class属性值
class_value = target_img.get_attribute("class")
print(class_value)  # 输出就是你要的FFVAD

driver.quit()

如果alt也不稳定,还可以用srcset里的固定域名部分来定位,比如//img[contains(@srcset, 'somewebsite.com')],只要找到一个不会随时间变化的属性即可。

方法2:结合Selenium + BeautifulSoup

如果你更习惯用BeautifulSoup的语法来解析HTML,也可以先让Selenium获取完整的页面源码,再传给BeautifulSoup处理:

from selenium import webdriver
from bs4 import BeautifulSoup
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()
driver.get("你的目标页面URL")

# 等待页面关键元素加载完成后再获取源码
WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.TAG_NAME, "img"))
)

# 获取页面源码
page_source = driver.page_source
soup = BeautifulSoup(page_source, "html.parser")

# 用稳定属性定位img元素
target_img = soup.find("img", alt="SOME TEXT")

# 提取class属性:注意如果有多个class值,会返回列表,单个值则直接是字符串
class_value = target_img["class"]
if isinstance(class_value, list):
    class_value = class_value[0]
print(class_value)  # 输出FFVAD

driver.quit()

一些关键提醒

  • 一定要用显式等待代替强制等待(比如time.sleep()),这样既能保证元素加载完成,又不会浪费不必要的等待时间。
  • 如果目标img的class属性可能包含多个值(比如class="FFVAD other-class"),Selenium的get_attribute("class")会返回空格分隔的字符串,而BeautifulSoup会返回列表,记得根据实际情况处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:47:15