从 Selenium for Python 中具有相同类的多个元素中获取文本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23924008/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get the text from multiple elements with the same class in Selenium for Python?
提问by user3685742
I'm trying to scrape data from a page with JavaScript loaded content. For example, the content I want is in the following format:
我正在尝试从带有 JavaScript 加载内容的页面中抓取数据。比如我要的内容格式如下:
<span class="class">text</span>
...
<span class="class">more text</span>
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(//span[@class="class"]').text
函数,但它只返回指定类的第一个实例。基本上,我想要一个像[text, more text]
等这样的列表。我找到了这个find_elements_by_xpath()
函数,但.text
最后会导致错误exceptions.AttributeError: 'list' object has no attribute 'text'
。
采纳答案by Yi Zeng
find_element_by_xpath
returns one element, which has text
attribute.
find_element_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.
find_elements_by_xpath()
返回所有匹配的元素,这是一个列表,因此您需要遍历并获取text
每个元素的属性。
all_spans = driver.find_elements_by_xpath("//span[@class='class']")
for span in all_spans:
print span.text
Please refer to Selenium Python API docs herefor more details about find_elements_by_xpath(xpath)
.
请参阅此处的Selenium Python API 文档以获取有关find_elements_by_xpath(xpath)
.
回答by jaz
This returns a list of items:
这将返回一个项目列表:
all_spans = driver.find_elements_by_xpath("//span[@class='class']")
for span in all_spans:
print span.text