我如何使用 selenium 和 python 查找节点及其子节点 [英] how do i find node and its child nodes using selenium with python

查看:338
本文介绍了我如何使用 selenium 和 python 查找节点及其子节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请让我知道如何使用文档中的 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打印 x

我也试过:

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

但都失败了.

解决方案

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

#!/usr/bin/env python从 contextlib 导入关闭from selenium.webdriver import Chrome as Browser # pip install selenium从 selenium.webdriver.support.ui 导入 WebDriverWait关闭(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('./*')对于儿童中的儿童:打印(<%s>%r"%(child.tag_name,child.text[:60]))

输出

u'如何使用 python 通过 selenium 处理对话框?<div>u'Networkx节点遍历'<div>u'如何设置 Selenium 以与 Visual Studio .NET 一起使用'<div>u'如何使用 Selenium 查找文本位置?<div>u使用 Selenium 的 Python API - 如何获取行数"<div>u'Python 中的硒'……[剪辑]……

Please let me know the code syntax how to use Node.childNodes from the documentation http://docs.python.org/library/xml.dom.html#module-xml.dom I am beginner to python and selenium. I have tried using:

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

I have also tried:

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

But both fail.

解决方案

elem is WebElement. You could use elem.find_elements_by_xpath() to select relevant child elements e.g.:

#!/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]))

Output

<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]...

这篇关于我如何使用 selenium 和 python 查找节点及其子节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆