[英]How to navigate to a sibling <p> element using selenium
I am trying to navigate to the sibling <p>
element using Selenium that has no id/class attributes. 我试图使用没有id / class属性的Selenium导航到兄弟
<p>
元素。 This is my HTML: 这是我的HTML:
<div class="content1">
<div class="bold">
<a href="test">test</a>
</div>
<p>
<span class="test two">Nuevo</span>
</p>
<div class="bold2">
<a href="test">test</a>
</div>
<p>
i want to get this text
</p>
</div>
This is my selenium code: 这是我的硒代码:
element = driver.findElement(By.xpath("content1/p[2]"));
can anyone help me correct my selenium code? 任何人都可以帮我纠正我的硒代码吗?
Your XPath isn't valid in the first place. 您的XPath首先无效。 Did you mean
.//div[@class='content1']/p[2]
? 你是说
.//div[@class='content1']/p[2]
?
Please try 请试试
element = driver.findElement(By.xpath(".//div[@class='content1']/p[2]"));
Here is another XPath you can also have a try, which doesn't require indexing. 这是另一个XPath,您也可以尝试,不需要索引。
element = driver.findElement(By.xpath(".//div[@class='content1']/div[@class='bold2']/following-sibling::p"));
Note that if the HTML isn't the real one you are testing, you might face other issues, the above XPaths only provide the logic. 请注意,如果HTML不是您正在测试的真实HTML,您可能会面临其他问题,上述XPath仅提供逻辑。
Option #1 (assuming that these are the first <p>
elements in the DOM): 选项#1 (假设这些是DOM中的第一个
<p>
元素):
element = driver.findElements(By.tagName("p")).get(1);
Option #2 : 选项#2 :
element = driver.findElement(By.xpath("//div[@class='content1']/p[2]"));
I've answered a question similar to this that could help you: 我已回答了类似的问题,可以帮助您:
Selecting Nth-of-type in selenium 在硒中选择Nth-type
If you are interested in CSS, I'd check this out. 如果你对CSS感兴趣,我会检查一下。 If you are wondering on how to use CSS with selenium, check out this blog post: http://ddavison.github.io/css/2014/02/18/effective-css-selectors.html
如果您想知道如何将CSS与selenium一起使用,请查看此博客文章: http : //ddavison.github.io/css/2014/02/18/effective-css-selectors.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.