【问题标题】:Getting WebElement while using another WebElement在使用另一个 WebElement 时获取 WebElement
【发布时间】:2018-08-02 06:24:17
【问题描述】:

我正在尝试使用 selenium 在另一个提取的元素中获取元素。但我得到了意想不到的结果。例如,下面的代码在循环中返回相同的“数据时间”和推文时间。注意“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).findElement(By.xpath("//div[1]/div[2]/div[1]/small/a/span") 总是指同一条推文,因此是相同的推文时间。为什么您没有从循环中的原始 tweet 对象中获取推文时间?

标签: java selenium xpath selenium-webdriver webdriver


【解决方案1】:

这是一个常见问题:要在每个 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

【讨论】:

    猜你喜欢
    • 2015-10-18
    • 2019-12-13
    • 1970-01-01
    • 1970-01-01
    • 2017-11-15
    • 1970-01-01
    • 1970-01-01
    • 2016-06-28
    • 1970-01-01
    相关资源
    最近更新 更多