Java Selenium:通过XPath提取Alt属性

Java Selenium:通过XPath提取Alt属性,java,selenium,xpath,Java,Selenium,Xpath,我正在Amazon上自动提取产品变体,我有以下HTML标记: <ul class="a-nostyle a-button-list a-horizontal a-spacing-top-micro swatches swatchesSquare imageSwatches"> <!-- Please note that in className never append a class with prefix as 'swatch'. It would brea

我正在Amazon上自动提取产品变体,我有以下HTML标记:

<ul
    class="a-nostyle a-button-list a-horizontal a-spacing-top-micro swatches swatchesSquare imageSwatches">
    <!-- Please note that in className never append a class with prefix as 'swatch'. It would break something in the twister JS -->
    <li id="color_name_0" class="swatchSelect" data-dp-url="" title="Click to select White">
        <span class="a-list-item">
            <div class="tooltip">
                <span class="a-declarative" data-swatchthumb-action="{"dimIndex":1,"dimValueIndex":0}" data-action="swatchthumb-action">
                    <span id="a-autoid-11" class="a-button a-button-thumbnail a-button-toggle">
                        <span class="a-button-inner">
                            <button id="a-autoid-11-announce" class="a-button-text" type="button">
                                <span class="xoverlay" />
                                <div class="">
                                    <div class="">
                                        <img style="height:36px; width:36px" alt="White"
                                            src="http://ecx.images-amazon.com/images/I/41IrdkWxWOL._SS36_.jpg"/>
                                    </div>
                                    <div class="" style=" " />
                                </div>
                            </button>
                        </span>
                    </span>
                </span>
            </div>
        </span>
    </li>
</ul>
现在我想提取每个项目的alt属性,但是当我尝试使用
getAttribute(“alt”)
时,它不会返回任何内容。在这种情况下,alt文本将为
“白色”
。我正在查看的产品是:。我正在使用Java。

您可以使用以下代码:

public class Stackoverflow extends Init {

    @Test
    public void testToGetAltAttribute() throws InterruptedException {
        System.out.println("Get Attribute....");

        // this element has alt attribute hence that will be displayed.
        assertAndVerifyElement(By.cssSelector("#landingImage"));
        System.out.println("\n#landingImage\n=====================");
        System.out.println(getAttributeOfGivenElement(By.cssSelector("#landingImage"), "alt"));

        // this element do not has alt attribute hence that will not be
        // displayed.
        // it will display msg "element do not have altattribute"
        assertAndVerifyElement(By.id("productTitle"));
        System.out.println("\n#productTitle\n=====================");
        System.out.println(getAttributeOfGivenElement(By.id("productTitle"), "alt"));

    }

    public String getAttributeOfGivenElement(By element, String attributeName) {

        WebElement webElement = getWebDriver().findElement(element);

        if (webElement.getAttribute(attributeName) != null) {
            return webElement.getAttribute("alt");

        } else {
            return "element do not have " + attributeName + "attribute";
        }
    }

    public void assertAndVerifyElement(By element) throws InterruptedException {
        boolean isPresent = false;

        for (int i = 0; i < 5; i++) {
            try {
                if (getWebDriver().findElement(element) != null) {
                    isPresent = true;
                    break;
                }
            } catch (Exception e) {
                // System.out.println(e.getLocalizedMessage());
                Thread.sleep(1000);
            }
        }
        Assert.assertTrue(isPresent, "\"" + element + "\" is not present.");
    }

}
公共类Stackoverflow扩展了Init{
@试验
public void testToGetAltAttribute()引发InterruptedException{
System.out.println(“获取属性…”);
//此元素具有alt属性,因此将显示该属性。
assertAndVerifyElement(由.cssSelector(“landingImage”);
System.out.println(“\n#landingImage\n============================”;
System.out.println(getattributeofgiveneElement(由.cssSelector(“#landingImage”),“alt”);
//此元素没有alt属性,因此不会
//显示。
//它将显示消息“元素没有altattribute”
assertAndVerifyElement(By.id(“productTitle”);
System.out.println(“\n#productTitle\n============================”;
System.out.println(getAttributeOfgiveElement(By.id(“productTitle”),“alt”);
}
公共字符串GetAttributeOfGiveElement(按元素,字符串attributeName){
WebElement WebElement=getWebDriver().findElement(元素);
if(webElement.getAttribute(attributeName)!=null){
返回webElement.getAttribute(“alt”);
}否则{
返回“元素没有”+attributeName+“属性”;
}
}
public void assertAndVerifyElement(按元素)引发InterruptedException{
布尔值isPresent=false;
对于(int i=0;i<5;i++){
试一试{
if(getWebDriver().findElement(元素)!=null){
isPresent=true;
打破
}
}捕获(例外e){
//System.out.println(e.getLocalizedMessage());
睡眠(1000);
}
}
Assert.assertTrue(isPresent,“\”+元素+“\”不存在。“);
}
}

当您有一个id属性时,我相信不需要转到xpath,除非您有许多具有相同id的按钮。但是,下面是如何获得img元素的属性-

WebElement btn = driver.findElement(By.id("a-autoid-11-announce"));
String imgColor = btn.findElement(By.tagName("img")).getAttribute("alt");

希望这对您有所帮助。

如果您想要所有颜色,您需要获取包含ALT属性的
IMG
元素。XPath在
按钮
处结束。请尝试下面的代码

List<WebElement> colors = driver.findElements(By.cssSelector("ul.imageSwatches img"));
for (WebElement color : colors)
{
    System.out.println(color.getAttribute("alt"));
}
List colors=driver.findElements(由.cssSelector(“ul.imageSwatches img”);
for(WebElement颜色:颜色)
{
System.out.println(color.getAttribute(“alt”);
}

CSS选择器被读取为查找具有类
imageSwatches
UL
标记,然后查找所有后代
IMG
标记。您可以循环浏览
IMG
标记的集合,并输出
ALT
文本。

在您发布的html中,没有id为“variation\u color\u name”的元素,并且按钮没有ALT属性。Img有它,所以您需要在XPath的末尾添加//Img。但是我需要将按钮值(即:a-autoid-11-announce)与Img的alt值(即:白色)关联起来—我正在尝试获取每个变体的XPath/颜色。然后您需要先找到按钮,然后再找到其中的Img。这应该有效:buttonFoundWithYourXPath.findElement(By.xpath(“//img”)).getAttribute(“alt”);您的HTML不是XML,甚至不是正确的HTML,请参见带有
a-declarative的(现在缩进)行。如前所述,不能将其用作XPath的输入,如果使用整理工具,则必须确保检查HTML是如何重写的,因为结构可能会被破坏/不同。