簡體   English   中英

Selenium 在 Java 中找不到元素

[英]Selenium not finding elements in Java

我正在嘗試使用 Selenium 的 API 搜索 WebElement。 我嘗試使用通配符來獲取頁面上的所有元素,然后遍歷它們,但它仍然沒有被打印。 有沒有辦法隱藏它們? 我不能簡單地搜索 id 或 name,因為它總是不同的 id。

這是我要檢索的示例:

<div class="question-body open-ended-single">
<input aria-labelledby="question-title-661489021" id="661489021" aria-required="false" data-sm-open-single="true" class="wds-input wds-input--lg qt-input_text text" name="661489021" size="50" value="">
</div>

以下是我測試過的一些代碼示例:

        List<WebElement> sectionList = driver.findElements(By.xpath("//div"));
        System.out.println(sectionList.size());

        for (WebElement ele : sectionList) {
            System.out.println(ele.getAttribute("id"));
        }

還將 //div 替換為 //input 等。該列表的大小為 25+,檢索元素也是如此,只是不是我需要的。

        List<WebElement> sectionList = driver.findElements(By.xpath("//div[contains(@id, 'open-ended-single')]"));
        List<WebElement> sectionList = driver.findElements(By.cssName("*"));

編輯:問題已解決。 感謝大家的幫助。 問題出在我的 HtmlUnitDriver 上,所以切換到 chrome headless 並且運行良好。

嘗試使用cssSelector

List<WebElement> sectionList = driver.findElements(By.cssSelector("div[class$='open-ended-single'] input[aria-labelledby^='question-title-']"));
        System.out.println(sectionList.size());

        for (WebElement ele : sectionList) {
            System.out.println(ele.getAttribute("id"));
        }

嘗試這個

List<WebElement> elems = driver.findElements(By.xpath(".//div[@class='question-body open-ended-single']"));
System.out.println("List Size is " + elems.size());
        for(WebElement e: elems ) {
            String idValue= e.findElement(By.xpath(".//input")).getAttribute("id");
            System.out.println(idValue);
        }

Output:

List Size is 1
661489021

這個 xpath 可能會起作用:

//div[contains(@class, 'question-body')]//input

您可能還需要在嘗試找到它之前使用顯式等待元素出現。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM