java Selenium WebDriver 按部分类名查找元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27049514/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Selenium WebDriver Finding Element by Partial Class Name
提问by user2150250
In the frame I'm working with, I have the following element:
在我正在使用的框架中,我有以下元素:
<div class="x-grid3-cell-inner x-grid3-col-expRepCol"> New session from client IP 192.168.5.3 (ST=/CC=/C=) at VIP 192.168.5.2 Listener /Common/Tomcat (Reputation=Unknown)</div>
As well as many other similar elements. I am trying to locate this element by partial name text and click it with the following code:
以及许多其他类似的元素。我正在尝试通过部分名称文本定位此元素,然后使用以下代码单击它:
String expectedText = "New session from client IP";
driver.findElement(By.className("div[class*='"+expectedText+"']")).click();
And I have also tried with cssSelector:
我也尝试过使用 cssSelector:
String expectedText = "New session from client IP";
driver.findElement(By.cssSelector("div[class*='"+expectedText+"']")).click();
But WebDriver keeps throwing an exception stating it's unable to locate that element. Any suggestions as to what could be the problem?
但是 WebDriver 不断抛出异常,指出它无法找到该元素。关于可能是什么问题的任何建议?
采纳答案by Richard
By.className
is looking for a class with the name entered.
By.className
正在寻找输入名称的类。
By.cssSelector
is looking for a match for the selector you entered.
By.cssSelector
正在为您输入的选择器寻找匹配项。
What you're attempting is to match the text of the div
against class
, which won't work.
什么你尝试是对文本匹配div
反对class
,这是行不通的。
You can try something like this:
你可以尝试这样的事情:
driver.findElement(By.xpath("//div[contains(text(),'"+expectedText+"')]")).click();
回答by Ajeet Verma
<div class="dd algo algo-sr Sr" data-937="5d1abd07c5a33">
<div class="dd algo algo-sr fst Sr" data-0ab="5d1abd837d907">
Above 2 are the HTML elements in yahoo search results. So if we wanna get these elements using partial class name with selenium python, here is the solution.
以上2是雅虎搜索结果中的HTML元素。所以如果我们想通过 selenium python 使用部分类名来获取这些元素,这里是解决方案。
driver.find_element_by_css_selector("div[class^='dd algo algo-sr']")
In the same way we can get any elements with partial match on any attribute values like class name, id etc.
以同样的方式,我们可以获得对任何属性值(如类名、id 等)进行部分匹配的任何元素。
find elements with css selector partial match on attribute values
回答by Anthony Long
I believe this will work:
我相信这会奏效:
driver.findElement(By.className("x-grid3-cell-inner x-grid3-col-expRepCol").click();