Selenium加载JSON定位器文件后元素点击报错求助
问题分析
核心问题是:JSON文件中存储的定位器是字符串格式,但Selenium的visibility_of_element_located需要接收一个包含定位策略(如By.XPATH)和定位表达式的元组,直接传入字符串会导致参数格式不匹配,引发报错。
解决方案
提供两种可靠解决方式,按需选择:
方式1:修改JSON结构(推荐,安全易维护)
调整JSON格式,拆分存储定位策略和表达式,加载后直接组装成Selenium需要的元组:
修改后的locator.json内容
{ "test": { "by": "XPATH", "value": "//*[@id='gb']/div/div[2]/a" } }
对应Python代码调整
from selenium import webdriver from selenium.webdriver.support.wait import WebDriverWait as WDW from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By import os import json testFile = os.path.join('./locator.json') testLoad = os.path.abspath(testFile) with open(testLoad,'r',encoding='UTF8') as f: testData = json.load(f) # 组装符合要求的定位器元组 locator = (getattr(By, testData['test']['by']), testData['test']['value']) webDriver = webdriver.Chrome(executable_path='./chromedriver') wdw = WDW(webDriver, 10) webDriver.get('https://www.google.com') wdw.until(EC.visibility_of_element_located(locator)).click()
方式2:解析原JSON字符串(不推荐,有安全风险)
若不想修改JSON结构,可通过eval()解析字符串,但eval会执行任意代码,仅在完全信任JSON内容时使用:
原JSON保持不变
{ "test":"By.XPATH, \"//*[@id='gb']/div/div[2]/a\"" }
对应Python代码调整
from selenium import webdriver from selenium.webdriver.support.wait import WebDriverWait as WDW from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By import os import json testFile = os.path.join('./locator.json') testLoad = os.path.abspath(testFile) with open(testLoad,'r',encoding='UTF8') as f: testData = json.load(f) # 解析字符串为元组 locator = eval(f"({testData['test']})") webDriver = webdriver.Chrome(executable_path='./chromedriver') wdw = WDW(webDriver, 10) webDriver.get('https://www.google.com') wdw.until(EC.visibility_of_element_located(locator)).click()
关键说明
- 方式1是更安全、可维护的方案,避免了
eval的潜在风险,也方便后续扩展ID、CSS_SELECTOR等其他定位策略。 - 方式2仅作为临时兼容方案,禁止在生产环境使用。
内容的提问来源于stack exchange,提问作者김희석
相关产品推荐
相关产品推荐

