【发布时间】:2016-06-25 22:14:45
【问题描述】:
我正在尝试使用 phantomjs 进行无头浏览器测试,我注意到像 driver.get(By.id("")) 这样的简单命令返回一个元素未找到异常。我确实设法找到了问题的根源。我做了一个 driver.getPageSource(),并注意到 phantomjs 没有检索或“看到”完整的页面 html。
下面的代码是我要运行的。我正在尝试在 Google 主页上找到搜索框。在浏览器中查看 HTML,可以看到搜索框的 id 是“lst-ib”。但是,在执行 getPageSource() 时,结果中缺少“lst-ib”。这没什么大不了的,因为我仍然可以按名称访问元素。但是在其他网页上,整个 HTML 块都丢失了,这导致 getPageSource() 中完全省略了整个元素。这使得测试这些元素变得不可能。
import static org.junit.Assert.*;
import java.io.File;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriverService;
import org.openqa.selenium.remote.DesiredCapabilities;
public class AccessMessageDataRetentionSettings
{
public WebDriver driver;
@Before
public void setup()
{
File f = new File("My path to the phantomjs executable");
System.setProperty("phantomjs.binary.path", f.getAbsolutePath());
DesiredCapabilities caps = new DesiredCapabilities();
caps.setJavascriptEnabled(true);
//caps.setCapability("takesScreenshot", false);
caps.setCapability(PhantomJSDriverService.PHANTOMJS_CLI_ARGS, new String[] {"--ssl-protocol=any", "--ignore-ssl-errors=true", "--web-security=false" });
driver = new PhantomJSDriver(caps);
driver.get("http://www.google.com");
//((JavascriptExecutor) driver).executeScript("var s=window.document.createElement('script'); s.src='path to my javascript file'; window.document.head.appendChild(s);");
//WebDriverWait wait = new WebDriverWait(driver, 10);
//driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//wait.until(ExpectedConditions.invisibilityOfElementLocated(By.id("lst-ib")));
}
@Test
public void test()
{
System.out.println(driver.getPageSource());
//driver.findElement(By.xpath("//input[@id = 'lst-ib']"));
driver.findElement(By.id("lst-ib"));
}
@After
public void afterTest()
{
driver.quit();
}
}
我尝试过的事情:将 webdriver 声明为 PhantomJSDriver,设置 DesiredCapabilities 的不同组合(包括将 ssl-protocol 设置为 tlsv1),通过 javascriptExecutor 执行 https://github.com/facebook/react/issues/945 建议的 javascript shim(这似乎没有正在做任何事情),并尝试 Selenium 中可用的各种等待。
PhantomJS 只是与现代网站不兼容,还是我完全遗漏了什么?
【问题讨论】:
-
Google 会根据请求浏览器提供不同的页面。因此,当在桌面浏览器或 PhantomJS 中打开页面时,页面会有所不同。此外,PhantomJS 有很多错误,所以这可能会起作用,但这并不是一个真正可以回答的问题。许多“现代”网站与 PhantomJS 配合得很好。有些根本不起作用。网站设计者在测试他们的页面时不会考虑到 PhantomJS 的兼容性。
标签: java selenium-webdriver phantomjs