Selenium没有在xpath上找到元素(Selenium not picking up found elements on xpath)

使用xpath或CSS找到元素列表(在浏览器控制台中的结果相同)

int alltips = driver.findElements(By.xpath("//div[@class='column medium-12']//div/ul/li")).size(); int alltips1 = driver.findElements(By.cssSelector("ul.feed-tips#Grid > li.feed-item")).size(); System.out.println(alltips); System.out.println(alltips1);

由于两种打印都得到了相同的结果(在一个页面上存在'li'容器中的21个)。但是,在selenium webdriver中运行时,我得到的结果相同,为零。 从控制台添加了截图

我做错了什么?

这是HTML的一部分:

<div class="column medium-12"> <h1>Free Tips</h1> <p>Here you'll always find the latest tips posted by our international community of sports betting tipsters. If you're ever in need of inspiration for a bet, this is the place to be! </p> <div class="row"> <ul class="feed-tips" id="Grid" data-sport="" data-country="" data- league="">

HTML下面的屏幕截图如下:

Found list of elements either with xpath or CSS (same results in browser console)

int alltips = driver.findElements(By.xpath("//div[@class='column medium-12']//div/ul/li")).size(); int alltips1 = driver.findElements(By.cssSelector("ul.feed-tips#Grid > li.feed-item")).size(); System.out.println(alltips); System.out.println(alltips1);

As a result of both printing got same result (that there are 21 of 'li' containers exist on a page) But, when put ran that in selenium webdriver, I got same result for both and it is zero. Added screenshot from console

What did I do wrong?

Here is a part of HTML:

<div class="column medium-12"> <h1>Free Tips</h1> <p>Here you'll always find the latest tips posted by our international community of sports betting tipsters. If you're ever in need of inspiration for a bet, this is the place to be! </p> <div class="row"> <ul class="feed-tips" id="Grid" data-sport="" data-country="" data- league="">

And below HTML looks like as on screenshot:

最满意答案

如果找不到元素, findElements不会引发错误,因此在调用此方法时可能找不到元素。

在调用findElements之前,可以通过使用WebDriverWait来等待ul元素可见

WebDriverWait wait = new WebDriverWait(driver, 10); wait.until(ExpectedConditions.visibilityOfElementLocated(By.id(#Grid)));

这会在等待超时10秒后等待超时。 之后,调用你的findElements方法。 此时你知道父母ul是可见的

int alltips = driver.findElements(By.xpath("//ul[@id='Grid']/li")).size();

findElements does not throw an error if no elements are found, so it is possible that the elements are not found at the time of calling this method.

You can wait for the ul element to be visible before calling findElements by using a WebDriverWait like this

WebDriverWait wait = new WebDriverWait(driver, 10); wait.until(ExpectedConditions.visibilityOfElementLocated(By.id(#Grid)));

This will wait up to 10 seconds before throwing a timeout. After that, call your findElements method. At this point you know that the parent ul is visible

int alltips = driver.findElements(By.xpath("//ul[@id='Grid']/li")).size();

更多推荐