Selenium Python:类型错误:"str"对象在尝试打印元素/元素文本时不可调用



我正试图通过转到最后一条消息来抓取一个电报通道,并打印其中的文本/将其存储在一个变量中以便稍后使用。

代码试用:

from cgitb import text
from http import server
from re import search
import selenium
import time
import sys
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
PATH = "/usr/local/bin/chromedriver"
driver = webdriver.Chrome(PATH)
driver.get("https://t.me/s/klfjezlkjfzlek")
test = driver.find_element(By.XPATH("//html//body//main//div//section//div//div//div//div[@class='tgme_widget_message_text js-message_text before_footer'][last()]"))
source_code = test.text
print(source_code)

我得到以下错误:

Traceback (most recent call last): 
File "/Users/usr/Desktop/tg.py", line 16, in <module>
text=driver.find_element(By.XPATH("//html//body//main//div//section//div//div//div//div[@class='tgme_widget_message_text js-message_text before_footer'][last()]"))     
TypeError: 'str' object is not callable
这是因为By.XPATH实际上是一个字符串。以下是Selenium文档的进一步阅读。

您可以使用find_element_by_xpath:

test = driver.find_element_by_xpath("//html//body//main//div//section//div//div//div//div[@class='tgme_widget_message_text js-message_text before_footer'][last()]")

driver.find_element(By.XPATH, "..."):

test = driver.find_element(By.XPATH, "//html//body//main//div//section//div//div//div//div[@class='tgme_widget_message_text js-message_text before_footer'][last()]")

希望能有所帮助!

Um在您的代码中键入:

test = driver.find_element(By.XPATH("//html//body//main//div//section//div//div//div//div[@class='tgme_widget_message_text js-message_text before_footer'][last()]"))

在错误消息中,它是:

text=driver.find_element(By.XPATH("//html//body//main//div//section//div//div//div//div[@class='tgme_widget_message_text js-message_text before_footer'][last()]"))

你的问题的一个快速答案是,你试图将字符串调用为函数

您使用的是SeleniumPython客户端,其中作为这行代码:

driver.find_element(By.XPATH("//html//body//main//div//section//div//div//div//div[@class='tgme_widget_message_text js-message_text before_footer'][last()]"))

Selenium Java客户端的。因此,TypeError


解决方案

您的有效代码行将是:

test = driver.find_element(By.XPATH, "//html//body//main//div//section//div//div//div//div[@class='tgme_widget_message_text js-message_text before_footer'][last()]")
source_code = test.text
print(source_code)

在一行:

print(driver.find_element(By.XPATH, "//html//body//main//div//section//div//div//div//div[@class='tgme_widget_message_text js-message_text before_footer'][last()]").text)

最新更新