无法找到cssSelector为的元素



我正在尝试访问这个div,稍后再单击它。

<div class="leaflet-marker-icon marker-cluster marker-cluster-small leaflet-clickable leaflet-zoom-animated" style="margin-left: -6px; margin-top: -6px; width: 12px; height: 12px; opacity: 1; transform: translate(702px, 396px); z-index: 396;" title="13 tracks listened in , UA">

以下是我要做的:

WebElement cluster = driver.findElement(By.cssSelector("marker-cluster-small"));

以下是我尝试做的:

WebElement cluster = driver.findElement(By.xpath("//div[@class='leaflet-marker-icon marker-cluster marker-cluster-small leaflet-clickable leaflet-zoom-animated']"));

这些方法都不起作用。第一个抛出"Unable to locate element"消息。第二个没有出现错误,但当我出现错误时:

cluster.click();

什么也没发生。我做错了什么?谢谢

你应该试试这个页面上的答案。我如何用XPath通过CSS类找到元素?。你应该能够通过只搜索"标记簇小"来做一些接近你的第一个答案的事情。希望这在某种程度上有所帮助。所以("//div[contains(@class, 'marker-cluster-small')]")

您也可以通过css找到它:

driver.find_element(:css, '.leaflet-marker-icon.marker-cluster.marker-cluster-small.leaflet-clickable.leaflet-zoom-animated')

但在这种情况下,conor的答案是最好的,因为类值太长了。

在CSS选择器中,您只是告诉它marker-cluster-small,但这不起作用,因为它在寻找元素标记,而不是类。为了让它看起来像一个类,你需要这样的点符号:

div.marker-cluster-small

.marker-cluster-small

记住,类上的CSS选择器比xpath选择器工作效率更高,因为您可以只命名一个类,即使元素也有其他类。

因此,我建议将其作为理想的定位器解决方案,简洁高效地使用CSS:

WebElement cluster = driver.findElement(By.cssSelector(".marker-cluster-small"));

附言CSS使用firefox上的firepath进行验证。

最新更新