如何使用Selenium Python获取<script>标签中的路径?
解决方法
你的问题核心在于:这个<script>标签类型为text/template,内部内容是模板代码,不会被浏览器解析成可交互的真实DOM节点,所以Selenium无法直接定位标签里的<input>元素。下面分两种场景给出具体方案:
场景1:提取模板中的路径占位符
如果只是要获取模板里写的路径占位符(比如{{groupInfo.picturePath}}),可以先定位<script>标签,再提取其文本内容并解析:
from selenium.webdriver.common.by import By import re # 定位目标script标签 script_tag = driver.find_element(By.ID, "TEMPLATE_GROUP_INFO_STRUCTURE") # 获取标签内的模板文本 template_content = script_tag.get_attribute("innerHTML") # 用正则提取data-picture-path的属性值 path_match = re.search(r'data-picture-path="([^"]+)"', template_content) if path_match: path_placeholder = path_match.group(1) print(path_placeholder) # 输出:{{groupInfo.picturePath}}
场景2:操作渲染后的真实上传按钮
如果你的需求是给文件上传框发送文件路径(即原代码里的send_keys操作),需要等待模板渲染为真实DOM元素后,再定位对应的<input>:
from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # 等待渲染后的文件上传input出现(最多等待10秒) wait = WebDriverWait(driver, 10) real_upload_input = wait.until( EC.presence_of_element_located((By.CLASS_NAME, "mdCMN09ImgInput")) ) # 获取渲染后的真实路径(若页面已填充该值) actual_path = real_upload_input.get_attribute("data-picture-path") print(actual_path) # 执行文件上传操作 real_upload_input.send_keys('./_220703_112705.mp4')
关键提示
- 模板标签内的代码只是字符串,不是可交互的DOM节点,直接用XPath定位内部元素必然失败。
- 若页面是动态渲染模板,必须等待渲染完成后再操作真实DOM;若仅需提取模板占位符,直接解析script标签的文本即可。
内容的提问来源于stack exchange,提问作者HOW TO
相关产品推荐
相关产品推荐

