从Selenium for Python中具有相同类的多个元素中获取文本? [英] Get the text from multiple elements with the same class in Selenium for Python?
问题描述
我正在尝试从具有JavaScript加载内容的页面上抓取数据.例如,我想要的内容具有以下格式:
I'm trying to scrape data from a page with JavaScript loaded content. For example, the content I want is in the following format:
<span class="class">text</span>
...
<span class="class">more text</span>
我使用了find_element_by_xpath(//span[@class="class"]').text
函数,但它仅返回指定类的第一个实例.基本上,我想要一个类似[text, more text]
的列表.我找到了find_elements_by_xpath()
函数,但是最后的.text
导致错误exceptions.AttributeError: 'list' object has no attribute 'text'
.
I used the find_element_by_xpath(//span[@class="class"]').text
function but it only returned the first instance of the specified class. Basically, I would want a list like [text, more text]
etc. I found the find_elements_by_xpath()
function, but the .text
at the end results in an error exceptions.AttributeError: 'list' object has no attribute 'text'
.
推荐答案
find_element_by_xpath
返回一个具有text
属性的元素.
find_element_by_xpath
returns one element, which has text
attribute.
find_elements_by_xpath()
返回所有匹配的元素,这是一个列表,因此您需要遍历并获取每个元素的text
属性.
find_elements_by_xpath()
returns all matching elements, which is a list, so you need to loop through and get text
attribute for each of the element.
all_spans = driver.find_elements_by_xpath("//span[@class='class']")
for span in all_spans:
print span.text
请参阅Selenium Python API文档此处有关find_elements_by_xpath(xpath)
的更多详细信息.
Please refer to Selenium Python API docs here for more details about find_elements_by_xpath(xpath)
.
这篇关于从Selenium for Python中具有相同类的多个元素中获取文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!