Selenium Webdriver在子元素中查找元素

时间:2012-12-27 05:50:11

标签: 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,但他的问题是由超时问题引起的。

有谁能帮我理解这里发生的事情?

4 个答案:

答案 0 :(得分:83)

当您使用//启动XPath表达式时,它会从文档的根目录中搜索,忽略您的父元素。你应该在.

之前加上表达式
element2 = driver.find_element_by_xpath("//div[@title='div2']")
element2.find_element_by_xpath(".//p[@class='test']").text 

答案 1 :(得分:1)

使用以下内容:

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

如果您有任何问题,请告诉我。

答案 2 :(得分:0)

这是您在CSS子类中搜索元素或标签的方式,我相信它也适用于多级情况:

示例HTML:

<li class="meta-item">
 <span class="label">Posted:</span>
 <time class="value" datetime="2019-03-22T09:46:24+01:00" pubdate="pubdate">22.03.2019 u 09:46</time>
</li>

例如,这就是获取pubdate标签值的方式。

published = driver.find_element_by_css_selector('li>time').get_attribute('datetime')

答案 3 :(得分:0)

Chrome Webdriver:

element = driver.find_element_by_id("ParentElement")
localElement = element.find_element_by_id("ChildElement")
print(localElement.text)