2015-12-06 34 views
2

我的测试Web服务器返回以下HTML:硒:获取列表中的元素含量为字符串

<ul class="dropdown-menu" id="dropdown-menu-id"> 
    <li><a href="">Pumpkins and Chocolate</a></li> 
    <li><a href="">Click to Nowhere</a></li> 
</ul> 

我试图使用Selenium打印<li>元素作为字符串的内容。例如:

'<a href="">Pumpkins and Chocolate</a>' 
'<a href="">Click to Nowhere</a>' 

我试过如下:

from selenium import webdriver 
browser = webdriver.Firefox() 
browser.get('http://localhost:8000') 
dropdown_list = self.browser.find_element_by_id('dropdown-menu-id') 
items = dropdown_list.find_elements_by_tag_name("li") 
for item in items: 
    print "Item text: >%s<" % item.text 

然而,这种打印出2个空字符串。我猜这可能是由于需要直接访问<a>标签。

<li>的内容作为字符串打印的正确方法是什么?

+0

嗯...为我工作。 –

+0

GetAttribute(“innerHTML”) – lloyd

回答

2

你的代码给出了下面的输出:

Item text: >Pumpkins and Chocolate< 
Item text: >Click to Nowhere< 

如果你想获得innerHTML的变化item.textitem.get_attribute("innerHTML")

Item text: ><a href="">Pumpkins and Chocolate</a>< 
Item text: ><a href="">Click to Nowhere</a>< 

为什么会得到空字符串的原因是因为Web要素是不可见item.text在这种情况下返回空字符串。

0

你需要使用find_elements_by_xpath( './/ul[@id="dropdown-menu-id"]/li/a')