如何在 webdriver 中获取元素的当前内容 [英] How can I get the current contents of an element in webdriver

查看:52
本文介绍了如何在 webdriver 中获取元素的当前内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一定是在考虑这个错误.

I must be thinking about this wrong.

我想在我使用 Webdriver/Selenium 2 访问的页面上获取元素的内容,在本例中为表单域

I want to get the contents of an element, in this case a formfield, on a page that I am accessing with Webdriver/Selenium 2

这是我损坏的代码:

 Element=driver.find_element_by_id(ElementID)
 print Element
 print Element.text

结果如下:

<selenium.webdriver.remote.webelement.WebElement object at 0x9c2392c>

(注意空行)我知道该元素有内容,因为我只是使用 .sendkeys 将它们填充在前面的命令中,并且我可以在脚本运行时在实际网页上看到它们.

(Notice the blank line) I know that element has contents since I just stuffed them in there with the previous command using .sendkeys and I can see them on the actual web page while the script runs.

但我需要将内容恢复为数据.

but I need to get the contents back into data.

我该怎么做才能读到这个?最好采用通用方式,以便我可以从各种类型的元素中提取内容.

What can I do to read this? Preferably in a generic fashion so that I can pull contents from varied types of elements.

推荐答案

我相信 prestomanifesto 走在正确的轨道上.这取决于它是什么元素.您需要将 element.get_attribute('value') 用于输入元素,并使用 element.text 返回元素的文本节点.

I believe prestomanifesto was on the right track. It depends on what kind of element it is. You would need to use element.get_attribute('value') for input elements and element.text to return the text node of an element.

您可以使用 element.tag_name 检查 WebElement 对象以找出它是哪种元素并返回适当的值.

You could check the WebElement object with element.tag_name to find out what kind of element it is and return the appropriate value.

这应该可以帮助您弄清楚:

This should help you figure out:

driver = webdriver.Firefox()
driver.get('http://www.w3c.org')
element = driver.find_element_by_name('q')
element.send_keys('hi mom')

element_text = element.text
element_attribute_value = element.get_attribute('value')

print element
print 'element.text: {0}'.format(element_text)
print 'element.get_attribute(\'value\'): {0}'.format(element_attribute_value)
driver.quit()

这篇关于如何在 webdriver 中获取元素的当前内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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