【问题标题】:NoSuchElementException found in Selenium webdriver while trying to use CssSelector尝试使用 CssSelector 时在 Selenium webdriver 中发现 NoSuchElementException
【发布时间】:2017-07-13 11:15:30
【问题描述】:

我正在尝试使用 cssSelector 而不是 xpath。我打开了 CNN 网站,并把 Politics 的xpath 放在了顶部。然后尝试使用cssSelector 选择它。我无法弄清楚我写的cssSelector 有什么问题。我收到NoSuchElementException

线程 "main" org.openqa.selenium.NoSuchElementException 中的异常:没有这样的元素:无法找到元素:{"method":"css selector","selector":"*[id='nav'] div :nth-child(2) div:nth-child(2) a:nth-child(3)"}

这里是代码

WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20,TimeUnit.SECONDS);
driver.get("http://cnn.com");
//driver.findElement(By.xpath("//*[@id='nav']/div[2]/div[2]/a[3]")).click();
driver.findElement(By.cssSelector("*[id='nav'] div:nth-child(2) div:nth-child(2) a:nth-child(3)")).click();

【问题讨论】:

  • 能否请您发布日志
  • 线程“main”中的异常 org.openqa.selenium.NoSuchElementException:没有这样的元素:无法找到元素:{“method”:“css selector”,“selector”:“* [id = 'nav'] div:nth-child(2) div:nth-child(2) a:nth-child(3)"}
  • 1.你真的有4个孩子吗? nth-child 编号从 0 开始,而不是 1
  • 2.元素是由 JS 静态加载还是动态加载?
  • 静态。 xPATH 不会改变。我尝试使用 nth-child 编号 0。 driver.findElement(By.cssSelector("*[id='nav'] div:nth-child(1) div:nth-child(1) a:nth-child(2 )“))。点击();我仍然得到错误。我要做的就是单击从 xPath 中给出的相同根元素中获取的政治部分

标签: java selenium selenium-webdriver css-selectors nosuchelementexception


【解决方案1】:

首先,如果可能,请避免使用:nth-child,而是使用类、ID 或其他(或多或少)明确的属性来查找元素。

例如,您提供的 XPath 将我指向 cnn.com 上的 Money 部分,而不是 Politics。

您应该使用[data-analytics-header='main-menu_politics'].nav-menu-links__link[href='/politics']

此外,您可以使用#nav 代替*[id='nav'].CLASSNAME 代替[class='CLASSNAME']w3schools.com 有一个方便的 CSS 选择器概述。

【讨论】:

    【解决方案2】:

    我非常支持 CSS 选择器,但在这种情况下,我可能会使用链接文本而不是 CSS 选择器。之后,我会使用像//div[@id='nav']//a[.='Politics'] 这样的XPath。如果我必须使用 CSS 选择器,我会使用 a[data-analytics-header='main-menu_politics']

    【讨论】:

      【解决方案3】:

      选择器中的第二个div:nth-child(2) 实际上应该是div:nth-child(3),第一个<a> 标签也是一个子标签。您也不应该将*cssSelctor 一起使用

      driver.findElement(By.cssSelector("[id='nav'] div:nth-child(2) div:nth-child(3) a:nth-child(2)")).click();
      

      你也可以使用nav-menu-links类作为起点

      driver.findElement(By.cssSelector("[class='nav-menu-links'] a:nth-child(2)")).click();
      

      或部分data-analytics-header属性

      driver.findElement(By.cssSelector("[data-analytics-header*='main-menu_politics']")).click();
      

      【讨论】:

      • 好吧,当我跟踪 HTML 时,CSSSelector 不遵循与 xPath 相同的规则。
      • 嗯,这个元素给了我世界部分而不是政治。
      • @Chetu19 不一定。
      • @Chetu19 你需要a:nth-child(2),而不是a:nth-child(3)。它在我的回答中。
      • 使用 *.在这种情况下您不需要它,但即使它在那里也不会伤害任何人。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-11
      • 1970-01-01
      • 2011-12-14
      • 2018-10-14
      • 2022-01-17
      • 2017-10-15
      • 1970-01-01
      相关资源
      最近更新 更多