【问题标题】:How to click on a <svg:image> element using Selenium and Python如何使用 Selenium 和 Python 点击​​ <svg:image> 元素
【发布时间】:2019-08-24 19:00:00
【问题描述】:

在下面提供了一个 xpath:

<svg:image xlink:href="some.svg" class="holder-38" width="24" height="268" preserveAspectRatio="none" x="426.7" y="473" type="image/svg+xml" data-ember-action="" data-ember-action-12238="12238">

我可以使用 xpath 访问它(没有标记为 '*'):

'//*[@class="holder-38"]'

但无法使用svg:image标签访问:

'//svg:image[@class="holder-38"]'

如何在此处指定标签?

【问题讨论】:

  • 我已经回滚了您对问题的上次编辑,因此问题标题更通用,对社区和未来的读者有帮助。

标签: python selenium svg xpath webdriverwait


【解决方案1】:

&lt;svg:image&gt;

&lt;svg:image&gt; 元素包括 SVG 文档中的图像。它可以显示raster image文件或其他SVG文件。 SVG 软件必须支持的唯一图像格式是 JPEG、PNG 和其他 SVG 文件。动画 GIF 行为未定义。

使用&lt;image&gt; 显示的SVG 文件是treated as an image,其中未加载外部资源,:visited 样式aren't applied,并且它们不能交互。要包含动态 SVG 元素,请尝试使用带有外部 URL 的 &lt;use&gt;。要在其中包含 SVG 文件并在其中运行脚本,请尝试在 &lt;foreignObject&gt; 中使用 &lt;object&gt;

注意:HTML 规范在解析 HTML 时将 &lt;image&gt; 定义为 &lt;img&gt; 的同义词。此特定元素及其行为仅适用于 SVG 文档或inline SVG


xlink:href

xlink:href 属性将指向资源的链接定义为引用 &lt;IRI&gt;。该链接的确切含义取决于使用它的每个元素的上下文。

自 SVG 2 起已弃用:不再推荐使用此功能。尽管某些浏览器可能仍然支持它,但它可能已经从相关的 Web 标准中删除,可能正在被删除,或者可能仅出于兼容性目的而保留。避免使用它,并尽可能更新现有代码;请参阅本页底部的兼容性表以指导您的决定。请注意,此功能可能随时停止工作。

注意:SVG 2 不再需要 xlink 命名空间,因此您应该使用 href 而不是 xlink:href


解决方案

到所需元素上的click(),您需要为所需的element_to_be_clickable 诱导WebDriverWait,您可以使用以下解决方案:

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//*[name()='svg:image' and starts-with(@class, 'holder') and contains(@xlink:href, 'some')]"))).click()

注意:您必须添加以下导入:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

【讨论】:

  • 但我不想使用 * 作为标签 - 你知道如何避免这种情况吗?
【解决方案2】:

尝试以下方式访问tag_name。

'//*[local-name()="svg:image"][@class="holder-38"]'

要点击元素,请使用Action Class。

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, 10).until(ec.presence_of_element_located(("xpath", '//*[local-name()="svg:image"][@class="holder-38"]')))
ActionChains(driver).move_to_element(elememnt).click().perform()

【讨论】:

    猜你喜欢
    • 2020-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-16
    • 2021-02-27
    • 2019-05-10
    相关资源
    最近更新 更多