2016-02-12 78 views
0

我试图在使用Selenium和Python网站报废,我得到了stucked在该网站所谓的“textarea的”领域。这是网站的HTML是如何调用在那里我试图提取文本的区域:硒得到textarea的错误

<textarea class="script" onclick="this.focus();this.select()" readonly="readonly" id="script"> 

此代码后说到,我想要得到的文本。下面是我使用的代码:

getCode = driver.find_elements_by_tag_name('textarea') 

我的问题是,它不承认以下代码文本:

getCode.submit() 
getCode.click() 
getCode.text() 

这是代码错误,我总是得到:

Traceback (most recent call last):
File "ScprL.py", line 55, in module
print (repr(getCode.text))
AttributeError: 'list' object has no attribute 'text'

我会apreciate您的帮助!

+0

如果你想要的第一个文本区域是你想要的文本区域 – Obsidian

+0

,你应该首先像这个'driver.find_elements_by_tag_name('textarea')[0]'从列表中提取webElement想要所有的textarea字段数据 –

回答

1

当您使用driver.find_elements你webElements列表您应该使用driver.find_element_by_tag_name代替

。你应该从列表中提取元素

elem = driver.find_elements_by_tag_name('textarea')[0] 
print element.text 

如果您在网页上的多个文字区域,那么你应该尝试找到你需要像下面

textareas = driver.find_elements_by_tag_name('textarea') 
for i, textarea in enumerate(textareas): 
    print '{} is at index {}'.format(textarea.text, i) 

的一个,然后使用适当的i值当你正在使用的驱动程序来获得textareas[i]

+0

就是这样!从'元素'中删除's',并且它不再获取列表,因此我可以得到我想要的简单文本。谢谢! –

+1

如果你需要一个单独的文本,那么你不需要使用列表...列表正在使用的地方,你需要迭代多个返回元素.. –

1

find_elements _by_tag_name( 'textarea的'),它会检索网络元素的列表。需要收集这些Web元素,然后逐个迭代,然后获取每个Web元素的文本。下面是Java中的例子,

List<WebElement> ButtonNamelist = driver.findElements(By.cssSelector(".locatorHere")); 

System.out.println(ButtonNamelist.size()); 

    for(int i=0;i<ButtonNamelist.size();i++){ 

System.out.println(ButtonNamelist.get(i).getText()); 

} 

谢谢你, 穆拉利

0

有两个功能硒每个定位器: “find_element 小号” 和 “find_element”。区别很简单:第一个返回满足选择器的元素列表,第二个返回第一个找到的元素。您可以阅读更多关于定位元素here的信息。

因此,您需要将功能更改为find_element_by_tag_name或从列表中检索第一个元素:find_element_by_tag_name()[0]