java Selenium CSS选择器语法,用于同时检查类和文本
问题是JAVA+Selenium:
我的HTML是:
<section class="d-menu d-outclass-bootstrap unclickable d-apps d-app-list">
<section class="standard-component image-sequence-button" tabindex="0" role="link">
<div class="image-region">
<div class="core-component image">...
</div>
<div class="sequence-region">
<div class="core-component section">
<div>
<section class="standard-component text hide-section-separator-line">
<div class="text-region">
<div class="core-component text">
<span class="main-text">BART Times</span>
<span class="sub-text">Provider</span>
</div>
</div>
</section>
<section class="standard-component speech-bubble hide-section-separator-line">...
<section class="standard-component text">...
</div>
</div>
</div>
<div class="button-region">
<div class="core-component button" tabindex="0" role="link">...
</div>
</section>
<section class="standard-component image-sequence-button" tabindex="0" role="link">...
<section class="standard-component image-sequence-button" tabindex="0" role="link">...
<section class="standard-component image-sequence-button" tabindex="0" role="link">...</section>
编辑:
所有<section class="standard-component image-sequence-button"...
具有完全相同的结构和层次结构(所有标记的属性相同)。唯一改变的是标签的文本值(例如span
)
第1部分:
我正在第二个section
标记中查找各种元素。所以,我想做的是得到<span class="main-text">
,因为业务需求,它有一个值BART Times
我已经知道如何通过xpath获取它:
我的xpath(通过firebug验证):
"//section//div[@class = 'sequence-region']//section[@class = 'standard-component text hide-section-separator-line']//span[@class = 'main-text' and text() = '%s']"
我可以通过检查%s值(例如BART时间)来获取span
标记
然而,出于设计考虑,我们被告知只使用CSS。因此,我试图为上面的xpath找到一个CSS对应项,但没有找到
下面的CSS
"section div.sequence-region section.standard-component.text.hide-section-separator-line span[class=main-text]"
返回所有section
标记下的所有span
标记
问题1:如何获取具有特定文本值的span
标记(xpath的%s部分)
我为最后一个span
标记尝试了一些不起作用的东西(根据firebug):
跨度。正文[text='BART Times']
span[class=main text][text='BART Times']
跨度。正文:包含('BART时代')
span[class=main text]:包含('BART时间')
跨度。主文本[text=“BART时代”]
span[class=main text][text=“BART时代”]
跨度。主文本[文本=\“BART时间\”]
span[class=main text][text=\'BART Times\']
span[text=“BART时间”]
span[文本=\“BART时间\”]
范围:包含('BART时间')
范围:包含(“BART时间”)
span:包含(\'BART Times\')
所以,基本上我想检查CSS选择器中span标记的class
和TEXT
值
第二部分:
然后我想得到<section class="standard-component image-sequence-button"...
元素,在那里我找到了<span class="main-text">
,然后在这个特定的section
标记中找到其他元素
问题2:
假设我通过CSS找到了问题1中的span
标记,那么如何获得section
标记(它是span
标记的超级父级)
如果CSS是不可能的,请为此提供一个xpath副本,作为暂时的解决方法
# 1 楼答案
关于问题1,这是不可能的,正如在这里的另一个答复中所述。这是关于主题的另一个线程:CSS selector based on element text?
关于问题2,XPath:Is there a CSS parent selector?中再次没有这样的父选择器。现在对于xpath对应项,您可以使用父轴(
parent::*
)或相同(..
)的快捷方式表示法,或者将span
选择器作为父轴的谓词(下面的第三个示例):请参阅下面的线程,了解使用XPath按CSS类匹配元素的一些更好(但更复杂)的替代方法,以防您遇到有关此主题的链接:How can I find an element by CSS class with XPath?
# 2 楼答案
CSS选择器无法基于文本进行选择。对Is there a CSS selector for elements containing certain text?的回答详细说明了原因
根据xpath中的类和文本进行选择:
//span[contains(@class, 'main-text') and text() = 'BART Times']