我正在尝试使用Selenium(版本2.28.0)在子元素中查找元素,但是Selenium似乎没有将搜索限制在子元素中。我是做错了还是有一种方法可以使用element.find在子元素中进行搜索?
例如,我创建了一个简单的测试网页,其中包含以下代码:
<!DOCTYPE html>
<html>
<body>
<div class=div title=div1>
<h1>My First Heading</h1>
<p class='test'>My first paragraph.</p>
</div>
<div class=div title=div2>
<h1>My Second Heading</h1>
<p class='test'>My second paragraph.</p>
</div>
<div class=div title=div3>
<h1>My Third Heading</h1>
<p class='test'>My third paragraph.</p>
</div>
</body>
</html>
我的Python代码(版本2.6)看起来像这样:
from selenium import webdriver
driver = webdriver.Firefox()
# Open the test page with this instance of Firefox
# element2 gets the second division as a web element
element2 = driver.find_element_by_xpath("//div[@title='div2']")
# Search second division for a paragraph with a class of 'test' and print the content
print element2.find_element_by_xpath("//p[@class='test']").text
# expected output: "My second paragraph."
# actual output: "My first paragraph."
如果我运行:
print element2.get_attribute('innerHTML')
它返回第二个division的html。 因此,selenium没有限制其搜索范围只在元素2中。我希望能够找到element2的子元素。这篇文章建议我的代码应该可以工作Selenium WebDriver访问子元素但他的问题是由于超时问题引起的。
有人可以帮我理解这里发生了什么吗?
element.find_element_by_whatever()
方法都是在指定元素的上下文中执行搜索。但是,find_element_by_xpath()
不是这样的。更多详细信息请参见 Selenium bug #403。 - Ross Patterson