如何修复Selenium的'find_element_by_xpath'属性错误,提取Stable Diffusion提示词
修复Selenium元素定位方法报错的方案
错误原因
你遇到的AttributeError是因为Selenium 4.x版本已移除find_element_by_xpath、find_elements_by_tag_name这类旧版元素定位方法,改用统一的find_element()和find_elements()方法配合By类来指定定位策略。
修复后的完整代码
from selenium import webdriver from selenium.webdriver.common.by import By # 新增导入By类 # 适配Google Colab环境的Firefox配置 options = webdriver.FirefoxOptions() options.add_argument('--headless') # 无头模式,适配无图形界面的Colab环境 options.add_argument('--no-sandbox') options.add_argument('--disable-dev-shm-usage') browser = webdriver.Firefox(options=options) browser.get('https://1234.gradio.live') while True: folder_path = input("Enter folder path to save text files: ") file_name = input("Enter file name to save text: ") if file_name == 'stop': break file_path = folder_path + '\\' + file_name + '.txt' # 替换旧的xpath定位写法 transition_div = browser.find_element(By.XPATH, '//div[@class="transition"]') # 替换旧的tag_name定位写法 p_elements = transition_div.find_elements(By.TAG_NAME, "p") p_texts = [p.text for p in p_elements] with open(file_path, 'w', encoding='utf-8') as f: for p_text in p_texts: f.write(p_text + '\n') print(f"Text saved in {file_path}") browser.quit()
关键修改点
- 新增导入
By类,用于指定元素定位的策略类型 - 将旧版的
find_element_by_xpath()替换为find_element(By.XPATH, 定位表达式) - 将旧版的
find_elements_by_tag_name()替换为find_elements(By.TAG_NAME, 标签名) - 针对Google Colab的无图形界面环境,添加了Firefox无头模式配置,避免运行时出现界面相关报错
内容的提问来源于stack exchange,提问作者Pokémon Trainer
相关产品推荐
相关产品推荐

