python - 使用 Python Selenium 获取跨度文本

标签 python selenium

这应该很容易,但我做不到。我正在使用 Google 主页运行一个小演示作为测试。

这是我的脚本:

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys
import time

browser = webdriver.Chrome()
browser.get("http://www.google.com") # Load page

time.sleep(0.2)

#top nav elements
elems = browser.find_elements_by_xpath("//span[contains(@class, 'gbts')]") 

for e in elems:
    print e.get_attribute('text')

browser.close()

它返回:

None
None
None
None
None
None
None
None
None
None
None

所以我认为它捕获了正确的元素,但也许不是正确的属性?没有把握。我也尝试打印 e.text() 但吐出来了:

Traceback (most recent call last):
  File "sample.py", line 14, in <module>
    print e.text()
TypeError: 'unicode' object is not callable

有什么想法吗?

*编辑 - 可能的解决方案? *

e.get_attribute('innerHTML') seems to work.

最佳答案

应该这样做:

from selenium import webdriver
browser = webdriver.Firefox()
browser.get("http://www.google.com")
for elem in browser.find_elements_by_xpath('.//span[@class = "gbts"]'):
    print elem.text

textWebElement 类的属性,因此不可调用。

class WebElement(object):
    """Represents an HTML element.       
    ...
    ...

    @property
    def text(self):
        """Gets the text of the element."""
        return self._execute(Command.GET_ELEMENT_TEXT)['value']

您有两种选择来获得第三场比赛:

#  1. Modify your xpath expression
browser.find_elements_by_xpath('(.//span[@class = "gbts"])[3]')[0].text

#  2. Access it by list index
browser.find_elements_by_xpath('.//span[@class = "gbts"])')[2].text

关于python - 使用 Python Selenium 获取跨度文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14590341/

相关文章:

java - 使用Windows文件上传上传文件夹中的所有文件 - Selenium

selenium - 配置 Capybara 以使用 Marionette WebDriver for Firefox

java - 如何在 selenium 中创建 driver.findelement( 再次函数) 的函数

python - Float16 在 numpy 中比 Float32 和 Float64 慢很多

Python 脚本打印 unicode,在 shell ` ` 中使用导致错误

python - 在 Python 类中将函数作为属性访问

python - CSS 和 JS 无法在 Flask 框架上运行

python - 将逗号分隔值的字符串列表写入 CSV

python-3.x - 如何使用 selenium 线程进行网页抓取?

python - 无法将下载的文件存储在相关文件夹中