在硒python

时间:2018-10-14 07:07:34

标签: javascript python html selenium

我有一个html代码,其中有一个SVG元素。 SVG内部有许多g元素,每个主题都有一些文本和rect元素以及一个标题标签。我想从其余元素中选择具有指定标题字符串的元素之一。

我尝试了一种基于find_elements_by_css_selector的方法,选择所有rect元素,然后返回父元素,并检查标题(.text)是否等于指定的文本。但是,这种方法失败了。

我选择的另一种方法是找到基于g类项目的所有元素,然后返回parent,然后检查它们的标题。但是,当我尝试这种方法时,遇到了错误“ StaleElementReferenceException('stale element reference:元素未附加到页面文档\ n \”。

我的html文件的简单版本如下:

<g class="class1">
    <title>some specified title</title>
    <rect x="809.875" y="9" width="461.5416666666667" height="4" class="element-body"></rect>
    <rect x="809.875" y="9" width="461.5416666666667" height="4" style="fill:#000080"></rect>
    <text x="814.875" y="8" class="svg-element-number" style="font-size:11px">080</text>
    <text x="792.875" y="8" class="svg-X" style="font-size:11px">xx1</text>
    <text x="1266.4166666666667" y="8" class="svg-X" style="font-size:11px">xx2</text>
    <image href="img/reg-changed.png" x="1256.4166666666667" y="10" height="13" width="15"></image>
</g>

3 个答案:

答案 0 :(得分:1)

尝试在下面的行中选择所需的元素:

driver.find_element_by_xpath('//*[name()="g" and *[name()="title" and .="some specified title"]]')

答案 1 :(得分:1)

您可以尝试使用xpath

 //*[name()='svg']/*[name()='g']/*[name()='title' and text()='some specified title']

如果您希望通过文本定位标题后访问g标签,请使用xpath轴,例如/ parent :: *

此处有更多信息:https://www.w3schools.com/xml/xpath_axes.asp

答案 2 :(得分:0)

有标记名的方法,
如果你只想
您可以使用它,

driver.find_elements_by_tag_name('title')