我有一小段 HTML 代码,当我使用 CSS 识别元素时,它失败了,而 XPath 可以正常工作。
我将 CSS 标识符用作“div#chart_1 div svg g.highcharts-button:nth-child(1)”,但在 XPath 正常工作时它不起作用。
HTML
<!DOCTYPE html>
<html>
<body>
<div id="overview-layout">
<div id="overview-body">
<div class="" id="overview-tabcontent-container">
<div data-highcharts-chart="7" class="chart" id="chart_1">
<div id="highcharts-26" class="highcharts-container">
<svg height="304" width="1154" version="1.1" xmlns="http://www.w3.org/2000/svg">
<rect zIndex="1"></rect>
<path zIndex="2"></path>
<g transform="translate(73,0)" style="cursor:default;text-align:center;" zIndex="7" class="highcharts-button">
<rect stroke-width="1" stroke="#68A" height="18" width="30" y="0.5" x="0.5" fill="url()" ry="0" rx="0"></rect>
<text zIndex="1" y="14" x="7.483333110809326">
<tspan x="7.483333110809326">1h</tspan>
</text>
</g>
<g transform="translate(103,0)" style="cursor:default;text-align:center;" zIndex="7" class="highcharts-button">
<rect stroke-width="1" stroke="#68A" height="18" width="30" y="0.5" x="0.5" fill="url()" ry="0" rx="0"></rect>
<text zIndex="1" y="14" x="7.483333110809326">
<tspan x="7.483333110809326">4h</tspan>
</text>
</g>
<g transform="translate(133,0)" style="cursor:default;text-align:center;" zIndex="7" class="highcharts-button">
<rect stroke-width="1" stroke="#68A" height="18" width="30" y="0.5" x="0.5" fill="url()" ry="0" rx="0"></rect>
<text zIndex="1" y="14" x="7.483333110809326">
<tspan x="7.483333110809326">8h</tspan>
</text>
</g>
<g transform="translate(163,0)" style="cursor:default;text-align:center;" zIndex="7" class="highcharts-button">
<rect stroke-width="1" stroke="#68A" height="18" width="30" y="0.5" x="0.5" fill="url()" ry="0" rx="0"></rect>
<text zIndex="1" y="14" x="7.391666889190674">
<tspan x="7.391666889190674">All</tspan>
</text>
</g>
</svg>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
最佳答案
definition对于 :nth-child
是:
The :nth-child(an+b) CSS pseudo-class matches an element that has an+b-1 siblings before it in the document tree, for a given positive or zero value for n, and has a parent element.
您有 g.highcharts-button:nth-child(1)
,它将选择 g.highcharts-button
,它是其父元素的第一个子元素,但您的 HTML 中没有这样的元素。 svg
元素的第一个子元素是 rect
。
我建议尝试 :nth-of-type
。它被定义为:
The :nth-of-type CSS pseudo-class matches an element that has an+b-1 siblings with the same element name before it in the document tree, for a given positive or zero value for n, and has a parent element.
所以你可以这样做:
div#chart_1 div svg g.highcharts-button:nth-of-type(1)
请注意,这不是一个完美的解决方案,因为 nth-of-type
只考虑元素类型,而不是 class
。如果您的 .highcharts-button
元素不是其父元素下的第一个 g
,那么上面的选择器仍然可能最终什么都不选择。
关于css - Selenium:XPath 可以找到元素但不能找到 CSS 为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27497938/