Python Selenium动态XPath报错:TypeError: 'str' object is not callable
问题分析与解决办法
错误原因
报错TypeError: 'str' object is not callable的核心问题是**By.XPATH的用法错误**:By.XPATH是Selenium定义的字符串常量(值为"xpath"),不是可调用的函数。你错误地将它当成函数,通过By.XPATH(...)的方式传入表达式,自然会触发字符串不可调用的错误。
两种解决方式
方式一:直接修正find_element调用格式
把出错的代码行改成标准的find_element调用写法,将定位策略和表达式分开传递,同时用f-string简化动态表达式拼接:
def load(self, name, id_entreprise): self.entreprise_selection.click_button() self.filter.set_text(name) # 修正后的写法:定位策略与表达式作为两个独立参数传入 self.driver.find_element(By.XPATH, f"//a[@id='company_{id_entreprise}']/div/span").click()
f-string会自动处理id_entreprise的类型转换(不管是整数还是字符串都能直接拼接),无需额外调用str()。
方式二:贴合原有封装风格(推荐)
如果你想保持类中locators的封装逻辑,可以动态生成定位器后再定位元素:
locators = { "entreprise_selection": ("ID", 'uidropdownCompanies'), "filter": ("XPATH", '//*[@id="filter"]') } def load(self, name, id_entreprise): self.entreprise_selection.click_button() self.filter.set_text(name) # 动态构造元素定位器 entreprise_load_locator = ("XPATH", f"//a[@id='company_{id_entreprise}']/div/span") # 用解包语法传递定位器参数 self.driver.find_element(*entreprise_load_locator).click()
这种方式和你原有代码的定位风格一致,后期维护更统一。
内容的提问来源于stack exchange,提问作者Michel Blaze
相关产品推荐
相关产品推荐

