【问题标题】:Trouble getting attributes of elements using Selenium | Python使用 Selenium 获取元素属性时遇到问题 | Python
【发布时间】:2021-04-08 12:53:33
【问题描述】:

每次我尝试获取 aria label 属性时,我之前都遇到过这个问题,这里的问题解决它根本没有帮助。我已经尝试过睡眠和列表理解(老实说,我不知道为什么它会起作用),但这就是我现在所处的位置,我的大脑是果冻:)。如果这是您想要建议的,则不能使用 xpath

messages = driver.find_elements_by_class_name('DMBLb')

buttons = message.find_elements_by_class_name('wpO6b')

for button in buttons:
   option_buttons = button.get_attribute('aria-label') 
   print(option_buttons) # returns none

【问题讨论】:

  • 1.你看到什么错误? 2. 添加 html 代码或链接到您正在测试的站点。
  • 您写道:如果您想建议顺便说一句,则不能使用 xpath。但接受了 xpath 的答案。

标签: python python-3.x selenium selenium-webdriver selenium-chromedriver


【解决方案1】:

根据您的问题和您共享的 HTML,该元素似乎是一个 React 元素,因此要检索属性 aria-label 您必须引入 WebDriverWait 以使所需元素可见,您可以使用以下解决方案:

 print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "element_xpath_you_found"))).get_attribute("aria-label"))

reference

【讨论】:

  • 给我一个 webdriverwait is not defined 错误,你确定这不是 JavaScript 吗?
  • 需要导入一些函数
  • from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC
  • 首先这不是你的主意,点击参考看看是谁的主意;)
【解决方案2】:

尝试等待列表中的所有元素。为此,您需要导入一些 selenium 模块:

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

wait = WebDriverWait(driver, 30)
wait.until(EC.visibility_of_all_elements_located(SelectBy.CLASS_NAME("wpO6b")))

buttons = message.find_elements_by_class_name('wpO6b')

for button in buttons:
   option_buttons = button.get_attribute('aria-label') 

另外,你想打印什么?试试option_buttons.text

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-08
    • 2021-08-05
    • 1970-01-01
    • 1970-01-01
    • 2014-11-29
    相关资源
    最近更新 更多