简体   繁体   English

如何使用Selenium Python定位基于React的元素

[英]How to locate React based elements using Selenium python

The Source code for the react element looks like below: react元素的源代码如下所示:

<g transform="translate(0 80)" style="transform: translate3d(0px, 80px, 0px);">
 <g class="sc-hMrMfs bRtpcM">
  <rect class="sc-drlKqa gwqdPs" x="-40" y="-20" height="40" width="80" rx="20" ry="20">
  <path class="sc-bIqbHp fiTNSa" d=" M -8 -6.666666666666667 l -6.666666666666667 6.666666666666667 l 6.666666666666667 6.666666666666667 ">
  <path class="sc-bIqbHp fiTNSa" d=" M 8 -6.666666666666667 l 6.666666666666667 6.666666666666667 l -6.666666666666667 6.666666666666667 ">
  <path class="sc-bIqbHp fiTNSa" d="M -13.333333333333334 0 h 26.666666666666668">
  <rect class="sc-jxGEyO lfiaEG" x="-40" y="-20" height="40" width="80">
 </g>
</g>

I'm trying to locate and right click the below element 我正在尝试找到并右键单击以下元素

<rect class="sc-jxGEyO lfiaEG" x="-40" y="-20" height="40" width="80">

using 使用

slider = driver.find_element_by_xpath('//*[@transform="translate(0 80)"]/g/rect[2]')
ActionChains(driver).context_click(slider).perform()

but this doesn't seem to work. 但这似乎不起作用。 Is there a better way to locate such react based elements using selenium webdriver? 有没有更好的方法使用Selenium Webdriver来定位基于反应的元素?

PS : The class name changes ie is dynamic, so I can't use the class name in the xpath. PS: 类名更改,即是动态的,所以我不能在xpath中使用类名。

You can avoid dynamic class names for a specific class: 您可以避免使用特定类的动态类名称:

:global(.yourClassName) {
  ...
}

That way, your element will keep the correct class name and you can use the class name for your selection. 这样,您的元素将保留正确的类名称,并且您可以使用该类名称进行选择。

Source: https://github.com/css-modules/css-modules 资料来源: https : //github.com/css-modules/css-modules

XPath has some limitations when used on a SVG DOM element. 当在SVG DOM元素上使用XPath时,存在一些限制。 So you are better off using a CSS selector: 因此,最好使用CSS选择器:

g[transform='translate(0 80)'] > g > rect:nth-child(2)

正如我们所看到的,您要定位的元素位于<g>标记内,该标记肯定位于<svg>标记内,因此我们可以尝试使用以下xpath来定位该元素:

"//*[name()='svg'//*[name()='g' and @transform='translate(0 80)']/*[name()='g']/*[name()='rect' and x='-40' and y='-20']"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM