Selenium Webdriver在子元素中查找元素

2024-05-03 15:21:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用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。所以硒并没有限制它对元素2的搜索。

我希望能够找到element2的子元素。这篇文章建议我的代码应该可以工作,但是他的问题是由超时问题引起的。

有谁能帮我了解这里发生了什么事吗?


Tags: 代码testdiv元素titlemyhtmlelement
3条回答

使用以下选项:

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

如果你有什么问题,请告诉我。

这就是在CSS子类中搜索元素或标记的方法,我相信它也适用于多层次情况:

HTML示例:

&13;
&13;
<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')

当您使用//启动XPath表达式时,它将忽略父元素从文档的根进行搜索。应该在表达式前面加上.

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

相关问题 更多 >