Selenium:无法理解 xPath

Selenium: Not able to understand xPath(Selenium:无法理解 xPath)
本文介绍了Selenium:无法理解 xPath的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有一些这样的 HTML:

I have some HTML like this:

<h4 class="box_header clearfix">
<span>
<a rel="dialog" href="http://www.google.com/?q=word">Search</a>
</span>
<small>
<span>
<a rel="dialog" href="http://www.google.com/?q=word">Search</a>
</span>
</h4>

我正在尝试使用 Selenium 在 Java 中获取 href.我尝试了以下方法:

I am trying to get the href here in Java using Selenium. I have tried the following:

selenium.getText("xpath=/descendant::h4[@class='box_header clearfix']/");
selenium.getAttribute("xpath=/descendant::h4[@class='box_header clearfix']/");

但这些都不起作用.它一直抱怨我的 xpath 无效.谁能告诉我我做错了什么?

But none of these work. It keeps complaining that my xpath is invalid. Can someone tell me what mistake I am doing?

推荐答案

你应该使用getAttribute来获取链接的href.您的 XPath 需要对最终节点的引用以及所需的属性.以下应该有效:

You should use getAttribute to get the href of the link. Your XPath needs a reference to the final node, plus the required attribute. The following should work:

selenium.getAttribute("xpath=/descendant::h4[@class='box_header clearfix']/a@href");

您还可以修改您的 XPath,使其更改更加灵活,甚至使用 CSS 来定位元素:

You could also modify your XPath so that it's a bit more flexible to change, or even use CSS to locate the element:

//modified xpath
selenium.getAttribute("//h4[contains(@class,'box_header')]/a@href");

//css locator
selenium.getAttribute("css=.box_header a@href");

这篇关于Selenium:无法理解 xPath的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

document.write() overwriting the document?(document.write() 覆盖文档?)
IE10 and Cross-origin resource sharing (CORS) issues with Image / Canvas(IE10 和 Image/Canvas 的跨域资源共享 (CORS) 问题)
Importing script with type=module from local folder causes a CORS issue(从本地文件夹导入 type=module 的脚本会导致 CORS 问题)
HTML crossorigin attribute for img tag(img 标签的 HTML 跨域属性)
MediaElementAudioSource outputs zeros due to CORS access restrictions local mp3 file(由于 CORS 访问限制本地 mp3 文件,MediaElementAudioSource 输出零)
Start calling js function when PC wakeup from sleep mode(PC从睡眠模式唤醒时开始调用js函数)