【问题标题】:How to get value from <h3> tag in Selenium WebDriver, Java如何从 Selenium WebDriver,Java 中的 <h3> 标记中获取值
【发布时间】:2012-08-10 13:41:31
【问题描述】:

我有html代码:

<div class="description">
<h3><strong>Samsung</strong> Galaxy SII (I9100)</h3>
<div class="phone_color"> ... </div>
...
</div>

我想使用 Selenium 2 (WebDriver) 从 /h3> 标签中获取值 Samsung Galaxy SII (I9100)

有人知道怎么做吗?

【问题讨论】:

    标签: java selenium webdriver


    【解决方案1】:

    这是用 C# 编写的,但将其转换为 Java 应该不难:

    /** Declare variables **/
    string descriptionTextXPath = "//div[contains(@class, 'description')]/h3";
    
    /** Find the element **/
    IWebElement h3Element = driver.FindElement(By.XPath(descriptionTextXPath));
    
    /** Grab the text **/
    string descriptionText = h3Element.Text;
    

    根据您是否有其他具有“描述”类的 div 元素,您可能需要进一步微调您的结果。


    以防万一:

    为了在页面上找到所有作为描述的 div 以供进一步使用,您可以这样做:

    /** Declare XPath variable **/
    string descriptionElementXPath = "//div[contains(@class, 'description')]";
    
    /** Grab all description div elements **/
    List<IWebElement> descriptionElements = driver.FindElements(By.XPath(descriptionElementXPath ));
    

    然后您可以使用 forloop 遍历每个元素并获取您需要的数据。

    以下是上述C#代码到Java的转换:

    /** 声明变量**/

    String descriptionTextXPath = "//div[contains(@class, 'description')]/h3";
    

    /** 查找元素**/

    IWebElement h3Element = driver.findElement(By.xpath(descriptionTextXPath));
    

    /** 抓取文字**/

    String descriptionText = h3Element.toString();
    

    或,

    String descriptionText = h3Element.getText();
    

    【讨论】:

    • 你也可以使用下面的xpath: //div[@class='description']/h3 或者,如果你想使用cssSelector,你可以使用如下: div.description > h3
    • 如何使用 CSS 选择器而不是 XPath 获取该元素?
    【解决方案2】:
    WebElement divElement = driver.findelement(By.classname("description"));
    String str = divElement.getText();
    System.out.println(str);
    

    这是完美的.. 它帮助.. 谢谢你:)

    【讨论】:

      【解决方案3】:
      WebElement divElement = driver.findelement(By.classname("description"));
      String str = divElement.getText();
      enter code here
      

      str 包含值。

      【讨论】:

        【解决方案4】:
        webDriver.findElement(By.tagName("h3"));
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-10-10
          • 1970-01-01
          • 2017-01-12
          • 1970-01-01
          • 2019-12-29
          • 2013-05-24
          • 2017-06-21
          • 2021-06-28
          相关资源
          最近更新 更多