错误:使用 Xpath 时出现“‘str’对象不可调用”

Kno*_*uns 2 python selenium xpath

我正在尝试在 Selenium 中编写一些测试,并且由于许多元素没有 ID 或 NAME 我尝试使用 Xpath。但是,无论如何,每当我使用 Xpath 时,我都会遇到相同的错误:

类型错误:“str”对象不可调用

以下是我测试的最简单的示例,它导致了相同的错误。

这是 Python 中的代码:

from selenium.webdriver.common.by import By
from selenium import webdriver

options = webdriver.ChromeOptions()
options.add_argument('ignore-certificate-errors')

driver = webdriver.Chrome(chrome_options=options)
driver.get('cannot_share_this_link/index.php')

driver.find_element(By.XPATH("//*[@id='sign']"))
Run Code Online (Sandbox Code Playgroud)

测试于:

<html>
    <head>
        <title>
            Comtest
        </title>
        <script src="comajax.js">
        </script>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js">
        </script>
    </head>

    <body>
         <div>
         <br>
         <input type="button" id="sign" value="Sign up" onclick="window.open('signup.php','popUpWindow','height=500,width=800,left=700,top=300,resizable=yes,scrollbars=no,toolbar=no,menubar=no,location=no,directories=no, status=yes');">
         <br>
         <input type="button" id="log" value="Log in" onclick="window.open('login.php','popUpWindow','height=500,width=800,left=700,top=300,resizable=yes,scrollbars=no,toolbar=no,menubar=no,location=no,directories=no, status=yes');">
         </div>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

编辑:我想指出的是,这个问题不是重复的,因为当我在寻找元素时,链接的线程显然正在寻找字符串作为输出。此外,两年前展示的方法现在会抛出弃用警告,如果它们甚至根本起作用的话(因为我根本无法让它工作,所以我无法告诉)。我已阅读链接的线程,在寻找解决方案的过程中我大约 30 次偶然发现了它。可能没有关于这个问题的帖子我没有读过,否则我不会发帖。

cru*_*dey 6

代替

driver.find_element(By.XPATH("//*[@id='sign']"))
Run Code Online (Sandbox Code Playgroud)

用这个 :

driver.find_element(By.XPATH, "//*[@id='sign']")
Run Code Online (Sandbox Code Playgroud)

内部方法签名:

def find_element(self, by=By.ID, value=None):
Run Code Online (Sandbox Code Playgroud)

预计使用 By then 并用逗号分隔,然后是值。

value 可以是您的 xpath,如果 By 是您提供的 xpath。

我建议诱导Explicit wait (WebDriverWait)

代码试用:

sign_in_ele = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//*[@id='sign']")))
sign_in_ele.click()
Run Code Online (Sandbox Code Playgroud)

进口:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
Run Code Online (Sandbox Code Playgroud)