【问题标题】:Selenium Htmlunitdriver not working although FirefoxDriver worksSelenium Htmlunitdriver 不工作,虽然 FirefoxDriver 工作
【发布时间】:2017-03-25 14:31:31
【问题描述】:

为什么这段代码使用 HtmlUnitDriver 会产生“失败”,而使用 FirefoxDriver 会产生“成功”?它正在尝试捕获在页面其余部分之后几秒钟加载的文本。我需要 HtmlUnitDriver 的“成功”。

//      WebDriver driver = new HtmlUnitDriver();
        WebDriver driver = new FirefoxDriver();
        driver.get("https://www.zoro.com/i/G1237047/");
        for (int i = 0; i < 360; i++) 
            if (driver.getPageSource().contains("<span id=\"availability")) {
                Thread.sleep(500);
                break;
            }
            Thread.sleep(500);
        if (driver.findElement(By.id("price-box-ships-from-zoro")).getText().contains("1 business day"))
            System.out.println("Success");
        else
            System.out.println("Failure");

【问题讨论】:

标签: selenium htmlunit-driver


【解决方案1】:

试试下面的代码:

  for (int i = 0; i < 360; i++) 
            if (driver.getPageSource().contains("<span id=\"availability")) {
                Thread.sleep(500);
                break;
            }

     String e = driver.findElement(By.xpath("//strong[contains(text(),'1 business day')]")).getText();
     System.out.println(e);
            Thread.sleep(500);
            if (e.contains("1 business day"))
                System.out.println("Success");
            else
                System.out.println("Failure");

也可以单独获取它们:尝试关注

第一行:

String a = driver.findElement(By.xpath("//div[@id='ships-from-lead-time-G1237047'][@class='ships-from-lead-time']")).getText();
String b = driver.findElement(By.xpath(".//strong[contains(text(),'1 business day.')]")).getText();
System.out.println(a);
System.out.println(b);

第二行:

String c =driver.findElement(By.xpath("//span[@id='price-box-ships-free']")).getText();
System.out.println(c);

第三行:

String d = driver.findElement(By.xpath("//span[@id='price-box-standard-ground']")).getText();
System.out.println(d);

【讨论】:

  • 这给出了以下例外。 “使用一些等待”是什么意思。线程“main”中的异常 org.openqa.selenium.NoSuchElementException: Unable to locate a node using //strong[contains(text(),'1 business day')] 有关此错误的文档,请访问:seleniumhq.org/exceptions/no_such_element.html Build信息:版本:'2.44.0',修订:'76d78cf',时间:'2014-10-23 20:03:00'
  • 上面编辑的代码对我来说很好,我也在控制台中获得了成功。
  • 第一个是重要的,返回一个空字符串作为成功案例 driver.findElement(By.id("ships-from-lead-time-G1237047"))。 getText() 和失败案例 driver.findElement(By.id("ships-from-lead-time-G2482308")).getText()。您使用的完整代码是什么?您是否指定浏览器仿真?
  • 你在说(driver.findElement(By.xpath("//strong[contains(text(),'1 business day')]")).getText().contains("1 business day"))
  • 你在控制台没有成功吗?我明白了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-25
  • 2014-12-11
  • 1970-01-01
  • 2020-08-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多