简体   繁体   English

使用文本定位元素

[英]Locating elements using text

In the following HTML I need to be able to select the element using the text located within, "SELECT PRODUCT". 在以下HTML中,我需要能够使用“选择产品”中的文本选择元素。

<div style="font-family: franklin-gothic-urw; font-weight: 400; font-style: normal; font-size: 19px; opacity: 1; color: rgb(255, 255, 255);">SELECT&nbsp;PRODUCT</div>

All resources lead me to something like this: 所有资源使我想到了这样的东西:

driver.findElement(By.cssSelector("div[textContent='SELECT PRODUCT'])

which does not work. 这不起作用。 I've tried various other xpaths and cssSelector and I can't seem to get it to locate the element. 我已经尝试了其他各种xpaths和cssSelector,但似乎无法找到它来定位元素。

Locating the element by it's absolute path works, but it's brittle and we don't want to locate it like that: 通过它的绝对路径来定位元素是可行的,但是它很脆弱,我们不想这样定位它:

html/body/div[3]/div[1]/div/div[3]/div/div/div/div/div[1]/div/div/div/div/div[2]/div[2]/div/div/div/div/div[2]/div

Selecting by style, aswell, will not work, as there are multiple elements on the page with the same format. 同样,按样式选择也不起作用,因为页面上有多个具有相同格式的元素。

I have tried to find an answer to this for a long while now. 我已经尝试了很长时间了。 What is the correct way to go about locating an element by text? 通过文本定位元素的正确方法是什么?

Locate the element by XPath: 通过XPath找到元素:

driver.findElement(By.xpath("//div[. = 'SELECT PRODUCT']"));

Or, as a workaround to tackle the &nbsp; 或者,作为解决&nbsp;的变通办法 inside the text : 在文字里面

driver.findElement(By.xpath("//div[starts-with(., 'SELECT') and contains(., 'PRODUCT')]"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM