从与 Selenium 中的模式匹配的所有元素中获取文本
我有一个包含以下形式元素的网站:
<td id="subject_23432423">content I want to read</td>
How do I use Selenium RC (特别是 Python 绑定) 来读取所有这些元素的内容?我已经检查了所有命令,虽然有很多选项可以查找单个元素,但没有一个命令似乎可以处理多个匹配的列表。例如,我可以使用以下命令查找特定元素的内容:
content = sel.get_text("td[@id='subject_23432423']")
但这假设我已经知道 id,但我不知道,因为它是动态生成的。
I have a site with elements of the form:
<td id="subject_23432423">content I want to read</td>
How do I use Selenium RC (with the Python bindings specifically) to read the content from all these elements? I've gone through all the commands, and while there's a lot of options to find a single element, none of the commands seem to handle lists of multiple matches. For example, I can find the content of a specific element using:
content = sel.get_text("td[@id='subject_23432423']")
but this assumes I already know the id, which I don't because it's generated dynamically.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我会做的是以下技术之一
或更有效的方式使用 BeautifulSoup 或lxml
What I would do is one of the following techniques
or for a more effiecent way to use BeautifulSoup or lxml
使用 Selenium 1 API 是不可能的,但是您可以调用 JavaScript,该 JavaScript 将使用 XPath
//td[contains(@id, "subject_")]
来定位元素(如果subject_
) code> 始终出现在生成的 id 中。我不确定 Selenium browserbot 是否为 IE 提供 XPath 支持,因此您可能仅限于具有本机支持的浏览器。在 Firefox 中,它将是:您需要在代码中将此脚本声明为字符串并通过 selenium.getEval 执行
但是,如果您能够切换到 Selenium 2 (WebDriver),您可以使用它的 API。您将需要使用
findElementsBy
传递 XPath//td[contains(@id, "subject_")]
,然后迭代返回的匹配数组并获取每个元素的文本It is impossible with the Selenium 1 API, however you can call a JavaScript that will locate elements using XPath
//td[contains(@id, "subject_")]
if thesubject_
is always present in the generated id. I am not sure if the Selenium browserbot provides an XPath support for IE, so you may me limited to the browsers that have native support. In Firefox it will be:You will need to declare this script as a string in your code and execute via selenium.getEval
However if you are able to switch to Selenium 2 (WebDriver), you can use its API. You will need to use the
findElementsBy
passing the XPath//td[contains(@id, "subject_")]
and then iterate through the returned array of matches and get the text of each element这在 Selenium 中肯定是可能的,因为这种类型的东西在 TestPlan(使用 Selenium 和 HTMLUnit 作为后端)中工作得很好。在这种情况下,简单的 TestPlan 脚本可能如下所示。
编写通知时会自动调用字符串转换,但存储在数组中也同样容易。
It certainly must be possible in Selenium since this type of thing works fine in TestPlan (which uses Selenium and HTMLUnit as the backend). In this case the simple TestPlan script might look like below.
The conversion to string is called automatically when writing a notice, but to store in an array it is just as easy.
在 Selenium 2 中,
我们可以检查
List subjects = driver.findElements(By.xpath("//td[contains(@id, 'subject_')]"))
int size = subject.size();
In Selenium 2
We can Check
List subjects = driver.findElements(By.xpath("//td[contains(@id, 'subject_')]"))
int size = subjects.size();