簡體   English   中英

Firefox in Python Selenium: driver.execute_script attempting to remove text characters with JQuery gives "SecurityError: The operation is insecure"

[英]Firefox in Python Selenium: driver.execute_script attempting to remove text characters with JQuery gives "SecurityError: The operation is insecure"

我正在使用 Selenium 3.141.0 和 Python,用於 Firefox 88.0 和 geckodriver 0.291。

以前,我能夠運行以下 JavaScript 執行以從 web 頁面中刪除不需要的字符(在本例中為 ®),如本答案所示:

driver.execute_script("var replaced = $('body').html().replace(/(®)/g,''); $('body').html(replaced);")

但是,在最近的某個時候,這不再有效,出現以下錯誤:

JavascriptException:消息:SecurityError:操作不安全。

Presumably, when updating Selenium, Firefox, or geckodriver, this function broke – unless there is something on the web page that I crawl (which is not mine) that has changed, that is making the script impossible to execute (I don't know web 頁面上的內容可能會導致這種情況)。

這個問題背后的原因可能是什么,是否可以“覆蓋” SecurityError 並執行腳本?

你有沒有嘗試過這樣的事情?

  1. Go 到 about:Config 並驗證dom.serviceWorkers.enabled設置為true
  2. 然后,將 go 設置為about:preferences#privacy並確保未選中Delete cookies and site data when Firefox is closed

似乎腳本正在嘗試更新/替換內容 - $('body').html(replaced); 也許在更新后它試圖下載一些內容,由於錯誤SecurityError: The operation is insecure被拋出。

要三角測量/調試此問題,您可以分解腳本執行並檢查發生異常的語句 -

  • driver.execute_script("var 替換 = $('body').html().replace(/(®)/g,'');")
  • driver.execute_script("$('body').html(replaced);")

此外,這種行為似乎與 Selenium/GeckoDriver 本身無關。 但是隨着 Javascript/JQuery 代碼的執行。

我在 JQuery 周圍發現了這兩個 StackOverflow 問題 + 上述錯誤,這可能會為您指明正確的方向 -

如果我找到其他方法來處理此行為,將更新此答案

感謝@Xtraterrestrial 在他們的回答中提供了幫助我解決問題的鏈接。 我已經賞金了。

為了清楚起見,我在這里提供我的特定解決方案。

鏈接答案之一所述, SecurityError的出現顯然是因為 JavaScript 試圖修改 web 頁面上的不安全元素,例如<input>

使用此答案中的代碼而不是使用的原始 JQuery,腳本現在查找 TextNodes 並僅修改那些。

var replaceTextInNode = function(parentNode){
    for(var i = parentNode.childNodes.length-1; i >= 0; i--){
        var node = parentNode.childNodes[i];

        //  Make sure this is a text node
        if(node.nodeType == Element.TEXT_NODE){
            node.textContent = node.textContent.replace(/(®)/g,'')
        } else if(node.nodeType == Element.ELEMENT_NODE){
            //  Check this node's child nodes for text nodes to act on
            replaceTextInNode(node);
        }
    }
};

replaceTextInNode(document.body);

在 Selenium 的 Python 中實現為:

driver.execute_script("var replaceTextInNode = function(parentNode){for(var i = parentNode.childNodes.length-1; i >= 0; i--){var node = parentNode.childNodes[i]; if(node.nodeType == Element.TEXT_NODE){node.textContent = node.textContent.replace(/(®)/g,'')} else if(node.nodeType == Element.ELEMENT_NODE){replaceTextInNode(node); }}}; replaceTextInNode(document.body);")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM