如何使用selenium和python找到节点及其子节点

时间:2012-03-03 18:07:21

标签: python selenium nodes

请让我知道如何使用文档中的Node.childNodes的代码语法 http://docs.python.org/library/xml.dom.html#module-xml.dom 我是python和selenium的初学者。我尝试过使用:

elem = self.browser.find_element_by_id("pie4")
x = elem.childNodes
print x 

我也尝试过:

self.dom.getElementsByTagName('path')[0].firstChild.data

但都失败了。

1 个答案:

答案 0 :(得分:2)

elemWebElement。您可以使用elem.find_elements_by_xpath()来选择相关的子元素,例如:

#!/usr/bin/env python
from contextlib import closing

from selenium.webdriver import Chrome as Browser # pip install selenium
from selenium.webdriver.support.ui import WebDriverWait

with closing(Browser()) as browser:
    browser.get('http://stackoverflow.com/q/9548523')
    elem = WebDriverWait(browser, timeout=10).until(
        lambda br: br.find_element_by_class_name('related'))
    children = elem.find_elements_by_xpath('./*')
    for child in children:
        print("<%s> %r" % (child.tag_name, child.text[:60]))

输出

<div> u'How to handle dialog box through selenium with python?'
<div> u'Networkx node traversal'
<div> u'How to set up Selenium to work with Visual Studio .NET using'
<div> u'How can I find text location with Selenium?'
<div> u"Using Selenium's Python API - How do I get the number of row"
<div> u'Selenium in Python'
...[snip]...