【问题标题】:How to extract the 'src' attribute as per the html through Selenium and Java如何通过 Selenium 和 Java 根据 html 提取“src”属性
【发布时间】:2018-08-24 14:16:44
【问题描述】:

我有一个 html 页面:

<video crossorigin="anonymous" class="" id="video" playsinline="true" 
       src="https://df.dfs.bnt.com/
       DEEAB832j06E9j413FjAA8Dj2zxc535DA2072E3jW01j15579/mp4- 
       hi/jFNf2IbBoGF28IzyU_WqkA,1535144598/zxxx/
       contents/1/8/1a57ae021173751b468cca136e0192.mp4? 
       rnd=0.38664488150364296"> 
</video>

通过 Selenium WebDriver 我尝试获取视频网址:

By videoLocator = By.id("video");
WebElement videoElement = driver.findElement(videoLocator);
String videoUrl = videoElement.getAttribute("src");

videoUrl - 总是返回 ""(为空)。

不过例如:

videoElement.getAttribute("crossorigin")

返回正确答案:“匿名”。

我已尝试使用 javascript 从 src 属性获取此 url:

String videoUrl = (String) js.executeScript("return document.getElementById( 'video' ).getAttribute( 'src' );");

但结果还是一样:""

我猜问题出在 crossorigin="anonymous" 但该怎么办呢?如何获取 src 值?

对不起,我的英语很差。

【问题讨论】:

    标签: java selenium selenium-webdriver webdriver getattribute


    【解决方案1】:

    尝试获取 innerHTML 属性。代码:

    By videoLocator = By.id("video");
    WebElement videoElement = driver.findElement(videoLocator);
    String videoUrl = videoElement.getAttribute("innerHTML");
    

    【讨论】:

      【解决方案2】:

      根据您提供的HTML,您需要诱导WebDriverWait,您可以使用以下解决方案:

      WebElement videoElement = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//video[@id='video' and @crossorigin='anonymous'][starts-with(@src,'http')]")));
      System.out.println(videoElement.getAttribute("src"));
      

      【讨论】:

      • Exception in thread "main" org.openqa.selenium.TimeoutException: Expected condition failed: waiting for value to contain "https". Current value: "null" (tried for 20 second(s) with 500 milliseconds interval)
      • @GSV 查看我更新的答案并告诉我结果。
      猜你喜欢
      • 2019-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-31
      • 2018-11-20
      • 1970-01-01
      • 2019-01-06
      • 1970-01-01
      相关资源
      最近更新 更多