python - 如何根据使用 Selenium 的 html 从使用 xpath 找到的元素中检索属性 aria-label 的值

标签 python selenium selenium-webdriver webdriver getattribute

我有以下 HTML 跨度:

<button class="coreSpriteHeartOpen oF4XW dCJp8">
    <span class="glyphsSpriteHeart__filled__24__red_5 u-__7" aria-label="Unlike"></span>
</button>

我还有一个 webElement 表示包含我使用 xpath 找到的这个跨度的按钮。如何从元素中检索 aria-label 值(不同于)?

我尝试过:

btn = drive.find_element(By.xpath, "xpath") 
btn.get_attribute("aria-label")

但它什么也没返回。如何检索元素的文本值 使用元素对象的“aria-label”属性?

最佳答案

aria-label 是 span 元素的属性,不是按钮。 你可以这样得到它:

btn = drive.find_element(By.xpath, "xpath") 
aria_label = btn.find_element_by_css_selector('span').get_attribute("aria-label")

或者,如果您的目标是找到 span 包含属性 aria-label="Unlike" 的按钮:

btn = drive.find_element(By.XPATH, '//button[./span[@aria-label="Unlike"]]')
#you can add class to xpath also if you need
btn = drive.find_element(By.XPATH, '//button[./span[@aria-label="Unlike"] and contains(@class,"coreSpriteHeartOpen)]')

关于python - 如何根据使用 Selenium 的 html 从使用 xpath 找到的元素中检索属性 aria-label 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52009771/

相关文章:

python - 使用 Python 和 simplekml 从 CSV 创建 KML 线串

python - 如何检查字符串是否包含列表中的单词

dom - 使用 Selenium 自动点击 JavaScript 链接

selenium - 如何使用 Selenium WebDriver 获取图像 src 名称

python - 将 Flask 应用程序部署到 Heroku 陷入重启循环

Python 在迭代过程中就地修改字典条目

java - 当父窗口关闭时无法读取 Selenium 中的子窗口元素

python - ENTER 按键使用 Selenium WebDriver 和 python

python - 元素不可见错误(Python、Selenium)

java - 在 Selenium 测试自动化中加载驱动程序可执行文件