首页 > 解决方案 > TypeError: 'str' 对象在使用 driver.page_source().text 时不可调用

问题描述

我正在尝试从网站中提取多个日期的表格。我正在使用以下代码来执行此操作。

from selenium import webdriver
from selenium.webdriver.chrome.options import Options


CHROMEDRIVER_PATH = 'C:/Users/asus/Downloads/chromedriver/chromedriver.exe'

options = Options()
options.add_argument('--headless')
options.add_argument('--disable-gpu')
driver = webdriver.Chrome(CHROMEDRIVER_PATH, chrome_options=options)

URL = 'URL'
driver.get(URL)

driver.find_element_by_id('calender1').click()

driver.find_element_by_css_selector(css_slctr).click() #css_selector for date
driver.find_element_by_id('show').click()
driver.page_source().text
# # print(html)

但是上面的代码给出了一个 TypeError 如下。

TypeError                                 Traceback (most recent call last)
<ipython-input-35-a6ffd4caf5cf> in <module>
      9 
     10 # driver.page_source().text
---> 11 driver.page_source().text
     12 # # print(html)
TypeError: 'str' object is not callable

我在 Rselenium 中尝试了相同的元素选择器,并且能够提取所需的表。由于我是 Python 新手,我不确定这个错误是什么意思!根据我在此处此处阅读的内容,在我看来,当我们尝试重新定义内置函数时会发生此错误(如果我误解了,请纠正我)。但我相信,我并没有在这里重新定义任何内置函数。那么为什么我会收到这个错误?我该如何解决这个问题?

标签: pythonseleniumtypeerror

解决方案


page_sourceWebDriver实例的属性。所以你不能page_source作为一个函数调用。您已经尝试过:

driver.page_source()

因此,您会看到错误:

---> 11 driver.page_source().text
TypeError: 'str' object is not callable

解决方案

作为解决方案,您可以使用以下任一解决方案:

  • 打印page_source

    print(driver.page_source)
    
  • 保存page_source在变量中并打印:

    html = driver.page_source
    print(html)
    

推荐阅读