为什么我不能使用类属性在Flipkart中定位元素?

huangapple go评论83阅读模式
英文:

Why am I not able to locate element in Flipkart using classname attribute?

问题

我正在使用 "class name" 属性来定位 Flipkart 中的元素,代码如下:

WebElement element = driver.findElement(By.className("_1QZ6fC _3Lgyp8"));

我遇到的错误是:

org.openqa.selenium.NoSuchElementException: 无法定位元素:._1QZ6fC\ _3Lgyp8

该元素的 HTML 代码如下:

<span class="_1QZ6fC _3Lgyp8">Electronics<svg width="4.7" height="8" viewBox="0 0 16 27" xmlns="http://www.w3.org/2000/svg" class="_3ynUUz"><path d="M16 23.207L6.11 13.161 16 3.093 12.955 0 0 13.161l12.955 13.161z" fill="#fff" class="_3Der3h"></path></svg></span>

目标网页元素和网站 - URL https://www.flipkart.com/ 中标题的 "Electronics" 类别。

英文:

I am using "class name" attribute to locate element in Flip-kart like this:

WebElement element = driver.findElement(By.className(&quot;_1QZ6fC _3Lgyp8&quot;));

The error I am getting is:

org.openqa.selenium.NoSuchElementException: Unable to locate element: ._1QZ6fC\ _3Lgyp8

HTML code of the element is as follows:

&lt;span class=&quot;_1QZ6fC _3Lgyp8&quot;&gt;Electronics&lt;svg width=&quot;4.7&quot; height=&quot;8&quot; viewBox=&quot;0 0 16 27&quot; xmlns=&quot;http://www.w3.org/2000/svg&quot; class=&quot;_3ynUUz&quot;&gt;&lt;path d=&quot;M16 23.207L6.11 13.161 16 3.093 12.955 0 0 13.161l12.955 13.161z&quot; fill=&quot;#fff&quot; class=&quot;_3Der3h&quot;&gt;&lt;/path&gt;&lt;/svg&gt;&lt;/span&gt;

Target webelement and website - The "Electronics" category of the header in the URL https://www.flipkart.com/

答案1

得分: 1

运行上述代码会产生以下错误:
org.openqa.selenium.InvalidSelectorException: 不允许使用复合类名

关于这个问题,您可以从这个早期的查询中找到更多详细信息 https://stackoverflow.com/questions/37771604/selenium-compound-class-names-not-permitted

除此之外,在指定的页面使用classname选项将导致选择多个元素,正如我们可以看到至少有7个具有相同classname的项目。

而不是这样,您可以使用xpath定位元素,类似于以下内容:

driver.findElement(By.xpath("//span[contains(.,'Electronics')]"));

英文:

Running the above line produces the following error:
org.openqa.selenium.InvalidSelectorException: Compound class names not permitted

Regarding this you can find more details from this earlier query https://stackoverflow.com/questions/37771604/selenium-compound-class-names-not-permitted

Besides using the classname option in the specified page will result in the selection of multiple elements, as we can see there are atleast 7 items having the same classname.

Instead of this, you can use xpath to locate the element, something like the following:

driver.findElement(By.xpath("//span[contains(.,'Electronics')]"));

huangapple
  • 本文由 发表于 2020年8月27日 14:53:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/63610635.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定