【问题标题】:How to extract the value of the data-id attribute of the button control using Selenium如何使用 Selenium 提取按钮控件的 data-id 属性的值
【发布时间】:2022-08-19 07:17:55
【问题描述】:

我在网页上有一个按钮控件

<button class=\"btn btn-mini download-attachment pull-right width100px margin-bottom-1px\" type=\"button\" data-id=\"48156\"><i class=\"icon-download\"></i>&nbsp;Download</button>

我想获取与之关联的数据ID。我正在使用硒。请建议我如何获取此按钮控件的数据 ID。

  • 您可以通过类名获取元素,然后获取属性data-id

标签: html selenium selenium-webdriver xpath webdriverwait


【解决方案1】:

打印值data-id您需要为visibility_of_element_located() 诱导WebDriverWait 的属性,您可以使用以下locator strategies 之一:

  • 使用C#XPath

    Console.WriteLine(new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.XPath("//button[contains(@class, 'download-attachment')][.//i[@class='icon-download']]"))).GetAttribute("value"));
    
  • 使用爪哇路径

    System.out.println(new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.elementToBeClickable(By.xpath("//button[contains(@class, 'download-attachment')][.//i[@class='icon-download']]"))).getAttribute("data-id"));
    
  • 使用Python路径

    print(WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[contains(@class, 'download-attachment')][.//i[@class='icon-download']]"))).get_attribute("data-id"))
    
  • 笔记:对于 客户,您必须添加以下导入:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-10
    • 1970-01-01
    • 1970-01-01
    • 2019-09-06
    • 2011-07-15
    • 1970-01-01
    • 2017-04-27
    • 1970-01-01
    相关资源
    最近更新 更多