2 回答

TA貢獻1826條經驗 獲得超6個贊
出于安全原因,Chrome 不允許您加載本地資源。您需要將文件放在驅動程序可以訪問的地方(網絡驅動器/服務器/存儲庫等),或者讀取文件并將其作為參數傳遞。
以下是第二個選項的工作原理:不要src在腳本元素上指定
je.executeScript(
$"var headID1 = document.getElementsByTagName('head')[0]; "
+ "var newScript1 = document.createElement('script'); "
+ "newScript1.type = 'text/javascript'; "
+ "var code = {fileText}; "
+ "newScript1.appendChild(document.createTextNode(code)); "
+ "headID1.appendChild(newScript1); "
+ "takeScreenShot();"
);

TA貢獻2039條經驗 獲得超8個贊
這是我使用 Selenium 執行/注入本地存儲的“.js”文件的方法:
File newJSFile = new File(path_to_local_js_file);
if (newJSFile.exists())
{
try
{
Scanner sc = new Scanner(new FileInputStream(newJSFile));
String js_TxtFile = "";
while (sc.hasNext()) {
String[] s = sc.next().split("\r\n");
for (int i = 0; i < s.length; i++) {
js_TxtFile += s[i];
js_TxtFile += " ";
}
}
try
{
((JavascriptExecutor)driver).executeScript(js_TxtFile);
}
catch (Exception ex)
{
System.out.println ("Exception when running Javascript: " + ex.toString());
}
}
catch (Exception ex)
{
System.out.println(ex.toString());
}
}
添加回答
舉報