![](/img/trans.png)
[英]executing Javascript using Selenium in python (Tkinter as GUI)
[英]Executing JavaScript in Python With Selenium
我目前正在嘗試刪除要自動執行的網頁上某個元素的屬性。 該名稱將始終有兩個變量,而第二個將始終是需要修改的變量。
為了工作,是否需要立即執行所有這些操作? 還是我需要將元素添加為參數? 我不確定如何進行調試,因為我對JavaScript不太熟悉。
以下是我當前的代碼:
js_one = "var x = document.getElementsByName(\"element\")"
js_two = "x[1].removeAttribute(\"readonly\")"
js_three = "x[1].removeAttribute(\"disabled\")"
driver.execute_script(js_one)
driver.execute_script(js_two)
driver.execute_script(js_three)
它給了我以下錯誤:
File "main.py", line 393, in main
driver.execute_script(js_two)
File "C:\Users\~\AppData\Local\Continuum\anaconda3\lib\site-packages\sele
nium\webdriver\remote\webdriver.py", line 629, in execute_script
'args': converted_args})['value']
File "C:\Users\~\AppData\Local\Continuum\anaconda3\lib\site-packages\sele
nium\webdriver\remote\webdriver.py", line 314, in execute
self.error_handler.check_response(response)
File "C:\Users\~\AppData\Local\Continuum\anaconda3\lib\site-packages\sele
nium\webdriver\remote\errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.JavascriptException: Message: ReferenceError: x is no
t defined
編輯我通過將代碼更改為以下內容解決了該問題:
js_one = 'document.getElementsByName("element")[1].removeAttribute("readonly");'
js_two = 'document.getElementsByName("element")[1].removeAttribute("disabled");'
driver.execute_script(js_one + js_two)
如果有人有更有效的方法來執行此操作,請隨時告訴我!
您正在一個接一個地執行三個JavaScript代碼段,在第二個代碼段中,您期望定義了變量x
,但並未定義,因此得到ReferenceError
:
selenium.common.exceptions.JavascriptException: Message: ReferenceError: x is not defined
我建議這樣嘗試:
driver.execute_script(";".join([js_one, js_two, js_three]))
這會將您的單個代碼段使用組合為一個;
並讓硒驅動程序執行它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.