簡體   English   中英

使用另一個WebElement時獲取WebElement

[英]Getting WebElement while using another WebElement

我正在嘗試使用硒將元素提取到另一個提取的元素內。 但是我得到了意想不到的結果。 例如,下面的代碼在循環中返回相同的“數據時間”和tweet時間。 請注意,“ data-item-id”不同,但“ data-time”相同。 我正在嘗試獲取與循環中的元素相關的“數據時間”。 知道我的錯誤是什么嗎?

    driver.get("https://twitter.com/CNN");

    List<WebElement> tweets = driver.findElements(By.xpath("//li[contains(@class, 'js-stream-item')]"));

    for (int i = 0; i < tweets.size(); i++) {
        System.out.println(tweets.get(i).getAttribute("data-item-id"));
        WebElement tweetTime = tweets.get(i).findElement(By.xpath("//div[1]/div[2]/div[1]/small/a/span"));
        System.out.println(tweetTime.getAttribute("data-time"));
        System.out.println(tweetTime.getText());
        System.out.println("-----------------------------------");
    }

產量

964597320301121536
1518812897
Feb 16
-----------------------------------
966636880702840834
1518812897
Feb 16
-----------------------------------
966638057217757184
1518812897
Feb 16
-----------------------------------
966636332721360896
1518812897
Feb 16
-----------------------------------
966633486797942784
1518812897
Feb 16
-----------------------------------
966630573740523520
1518812897
Feb 16
-----------------------------------
966627896474460160
1518812897
Feb 16
-----------------------------------
966624849732034560
1518812897
Feb 16
-----------------------------------
966622030526402561
1518812897
Feb 16
-----------------------------------
966611062052343808
1518812897
Feb 16
-----------------------------------
966605886792830976
1518812897
Feb 16
-----------------------------------
966604093719482373
1518812897
Feb 16
-----------------------------------
966602318522265600
1518812897
Feb 16
-----------------------------------
966600547364233216
1518812897
Feb 16
-----------------------------------
966598713903865857
1518812897
Feb 16
-----------------------------------
966594943216242688
1518812897
Feb 16
-----------------------------------
966591153700245505
1518812897
Feb 16
-----------------------------------
966587390805577730
1518812897
Feb 16
-----------------------------------
966587263147741185
1518812897
Feb 16
-----------------------------------
966585227618541568
1518812897
Feb 16
-----------------------------------
966583600673099777
1518812897
Feb 16
-----------------------------------

這是一個普遍的問題:要在每個tweets.get(i)查找元素,您應該在XPath的開頭指定代表當前節點(上下文)的點:

".//div[1]/div[2]/div[1]/small/a/span"  # first node found inside current tweet

代替

"//div[1]/div[2]/div[1]/small/a/span"  # first node found in DOM

暫無
暫無

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

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