【问题标题】:Selecting image inside SVG tag in selenium在硒中选择SVG标签内的图像
【发布时间】:2015-09-27 12:19:28
【问题描述】:

我刚刚开始在 selenium 中工作,并且卡在一个点上并且需要帮助。 这是我的html。我正在使用 python selinium

<div id="d3_tree">
  <svg>
    <g>
      <g class="node vm node_pe">
        <image class="mainNode" xlink:href="images/edge.png"> </image>
        <image xlink:href="images/gate.png"></image>
      </g>
      <g class="node vm node_pe">
        <image class="mainNode" xlink:href="images/edge.png"> </image>
        <image xlink:href="images/gate.png"></image>
      </g>
    </g>
  </svg>
</div>

我想获取所有 vm node_pe 的图像标签,以便检查哪个节点有图像。

这些是我尝试使用的 xpath,其中 i 是 xpath 上的循环。

"//div[@id='d3_tree']/*[name()='svg']/*[name()='g']/*[name()='g["+str(i)+"]']/*[name()='image[2]']"

xpath 以上返回 NONE

"//div[@id='d3_tree']/*[name()='svg']/*[name()='g']/*[name()='g["+str(i)+"]']"

返回 1 个元素,但无法获取任何属性。

"//*[contains(@class, 'node vm node_pe')]"

返回所有元素,但 get_attribute("innerHTML") 返回 NONE

任何帮助将不胜感激 谢谢

【问题讨论】:

  • //div[@id='d3_tree']//g[@class = 'node vm node_pe']/image
  • 我通过 xpath 测试器尝试并在添加关闭 &lt;/div&gt; 后接收 Not well formed: http://www.w3.org/TR/1999/REC-xml-names-19990114#AttributePrefixUnbound?image&amp;xlink:href&amp;xlink
  • 忘记添加
    但它在原始代码中。
  • 试试这个://div[@id='d3_tree']/g/g[1]/image[1]
  • 标签: python selenium xpath svg


    【解决方案1】:

    这个 XPATH 应该可以工作:

    //*[@id="d3_tree"]/svg/g/g/*[contains(@class, 'mainNode')]/@xlink:href
    

    或者你可以这样做:

    images = WebDriverWait(driver, 2).until(lambda driver: driver.find_elements_by_css_selector('#d3_tree image.mainNode'))
    for image in images:
        print(image.get_attribute('xlink:href'))
    

    要检查一个节点是否有图像,你可以检查属性是否为无。

    if(image.get_attribute('xlink:href') is None):
        print("attribute is none")
    

    【讨论】:

    • 第二个图像标签没有附加类。所以它不会得到所有的图像。
    • //*[@id="d3_tree"]/svg/g/g/image[2]/@xlink:href 获取第二个图片标签
    • 或更改图片 css_selector : images = WebDriverWait(driver, 2).until(lambda driver: driver.find_elements_by_css_selector('#d3_tree image:nth-child(2)'))
    猜你喜欢
    • 1970-01-01
    • 2015-10-22
    • 2020-04-05
    • 2021-05-05
    • 2021-02-03
    • 1970-01-01
    • 1970-01-01
    • 2021-11-11
    • 1970-01-01
    相关资源
    最近更新 更多