【问题标题】:How to access to 'rect' type element through Selenium-Python如何通过 Selenium-Python 访问“rect”类型的元素
【发布时间】:2019-08-24 16:55:59
【问题描述】:

dom中有一个rect对象:

<rect class="slv-blank" id="id123" height="8.8" stroke-width="1px" width="18.8" x="59.2" y="37.5"></rect>

我正在尝试使用以下代码进行搜索:

WebDriverWait(driver, 1).until(ec.presence_of_element_located(("xpath", '//rect[@id="id123"]'))).click()

这不起作用。

但以下是:

WebDriverWait(driver, 1).until(ec.presence_of_element_located(("xpath", '//*[name()="rect"][@id="id123"]'))).click()

关于为什么第一个不起作用的任何线索?

【问题讨论】:

  • 你说的不起作用是什么意思?当你尝试时会发生什么?

标签: python selenium svg xpath svg-rect


【解决方案1】:

&lt;rect&gt;

&lt;rect&gt; 元素是一个基本的SVG 形状,它创建矩形,由角的位置、宽度和高度定义。矩形的角可能是圆的。

一个例子:

<svg viewBox="0 0 220 100" xmlns="http://www.w3.org/2000/svg">
  <!-- Simple rect element -->
  <rect x="0" y="0" width="100" height="100" />

  <!-- Rounded corner rect element -->
  <rect x="120" y="0" width="100" height="100" rx="15" ry="15" />
</svg>

属性

&lt;rect&gt; 元素中的attributes 如下:

  • x:这个属性决定了矩形的x坐标。
    • 值类型:| ;默认值:0;动画:是的
  • y:这个属性决定了矩形的y坐标。
    • 值类型:| ;默认值:0;动画:是的
  • width:这个属性决定了矩形的宽度。
    • 值类型:自动|| ;默认值:自动;动画:是的
  • height:这个属性决定了矩形的高度。
    • 值类型:自动|| ;默认值:自动;动画:是的
  • rx:这个属性决定了矩形的水平角半径。
    • 值类型:自动|| ;默认值:自动;动画:是的
  • ry:这个属性决定了矩形的垂直角半径。
    • 值类型:自动|| ;默认值:自动;动画:是的
  • pathLength:这个属性可以指定路径的总长度,以用户为单位。
    • 值类型:;默认值:无;动画:是的

注意:从 SVG2 开始的 x、y、width、height、rx 和 ry 是几何属性,这意味着这些属性也可以用作该元素的 CSS 属性。


这个用例

由于&lt;rect&gt; 元素是一个SVG 元素,因此要定位此类元素,您必须在使用 访问元素时明确指定SVG namespace,如下所示:

  • 对于&lt;svg&gt; 元素:

    //*[name()="svg"]
    
  • 对于&lt;g&gt; 元素:

    //*[name()="svg"]/*[name()="g"]
    
  • 对于&lt;rect&gt; 元素:

    //*[name()="svg"]/*[name()="g"]/*[name()="rect"]
    //*[name()="svg"]/*[name()="rect"]
    

参考文献

您可以在

中找到一些相关的详细讨论

【讨论】:

  • 谢谢 - 这解释得很好
  • 您推断存在一个名称空间,并建议“明确指定 SVG 名称空间”,但是您的 XPath 表达式不会这样做。 Niether //*[name()="svg"]/*[name()="g"]/*[name()="rect"] 也不是 //*[name()="svg"]/*[name()="rect"]
【解决方案2】:

使用Action 类或JavaScript Executor。

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.common.action_chains import ActionChains
elememnt=WebDriverWait(driver, 1).until(ec.presence_of_element_located(("xpath", '//*[@id="id123"]')))
ActionChains(driver).move_to_element(elememnt).click().perform()

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.common.action_chains import ActionChains
elememnt=WebDriverWait(driver, 1).until(ec.presence_of_element_located(("xpath", '//*[@id="id123"]')))
driver.execute_script("arguments[0].click();",elememnt)

【讨论】:

    猜你喜欢
    • 2021-09-15
    • 1970-01-01
    • 1970-01-01
    • 2021-06-15
    • 2014-03-12
    • 2021-05-18
    • 2020-11-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多