python - Selenium Webdriver 在子元素中查找元素

标签 python xpath selenium

我正在尝试使用 Selenium(版本 2.28.0)在子元素中搜索元素,但 selenium des 似乎并未将其搜索限制在子元素中。我做错了还是有办法使用 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')

它从第二个分区返回 html。所以 selenium 并没有将其搜索限制在 element2 上。

我希望能够找到 element2 的子元素。这篇文章表明我的代码应该可以工作 Selenium WebDriver access a sub element但他的问题是由超时问题引起的。

谁能帮我理解这里发生了什么?

最佳答案

如果您使用 // 开始 XPath 表达式,它将从文档的根目录开始搜索。要相对于特定元素进行搜索,您应该在表达式前面加上 .:

element2 = driver.find_element_by_xpath("//div[@title='div2']")
element2.find_element_by_xpath(".//p[@class='test']").text

关于python - Selenium Webdriver 在子元素中查找元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14049983/

相关文章:

python - lxml:元素上的 XPath 和命名空间

javascript - 使用 Nightwatch 进行演示 - 通过配置减慢断言

java - driver.wait() 抛出 IllegalMonitorStateException

python - AzureException : Incorrect padding. 遵循 Azure 教程即可

Python:递归方法回滚变化?

python - 使用 xpath 获取当前元素内的元素

javascript - Selenium 的 PhantomJS Webdriver 未在 ReactJS 中加载页面

python - 向 JSON 对象 Hook 添加类型提示的正确方法

python - 找不到满足opencv-python要求的版本

java - 如何在 Chrome 下载中访问父级下角色的 (Xpath) 值