
在Python 中使用Selenium 執行JavaScript
在提供的程式碼片段中,目標是在Python 中使用Selenium 執行特定的JavaScript 片段。此程式碼片段旨在透過與 Web 應用程式互動來自動化工作流程。但是,嘗試使用 selenium.GetEval 執行 JavaScript 失敗,並出現 AttributeError。
解決方案:
使用 Python 在 Selenium 中執行 JavaScript 的正確方法是 browser.execute_script ()。若要解決此問題,請將 selenium.GetEval() 替換為 browser.execute_script()。
修訂程式碼:
<code class="python"># Import necessary modules
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
# Get user inputs
patch = input("Enter patch number\n")
rel = input("Enter release\n")
plat = input("Enter port\n")
# Launch Firefox browser
browser = webdriver.Firefox()
# Navigate to the target web page
browser.get("xxxxxxxxxxxxxxxxx")
# Find and populate various input fields
pdtfamily = browser.find_element_by_id("prodFamilyID")
pdtfamily.send_keys("Database & Tools" + Keys.TAB)
time.sleep(5)
pdt = browser.find_element_by_id("productID")
pdt.send_keys("Intelligent Agent" + Keys.TAB)
time.sleep(5)
pdt1 = browser.find_element_by_id("patchCacheChkBxID")
pdt1.send_keys(Keys.SPACE)
time.sleep(5)
pdt7 = browser.find_element_by_id("M__Idf")
pdt7.send_keys(plat)
pdt8 = browser.find_element_by_id("M__Idg")
pdt8.send_keys("American English")
# Execute the desired JavaScript code
browser.execute_script("submitForm('patchCacheAdd',1,{'event':'ok'});return false;")
# Close the browser
browser.close()</code>透過使用browser.execute_script(), JavaScript 程式碼「submitForm('patchCacheAdd',1,{'event':'ok '});return false;」可以在Python編寫的Selenium腳本中成功執行。
以上是如何使用 Python 在 Selenium 中執行 JavaScript 程式碼?的詳細內容。更多資訊請關注PHP中文網其他相關文章!