it-swarm-id.com

Menjalankan javascript di Selenium menggunakan Python

Saya benar-benar baru di Selenium. Saya ingin menjalankan cuplikan javascript dalam kode berikut (seperti yang dikomentari dalam kode), tetapi tidak dapat melakukannya. Tolong bantu.

from Selenium import webdriver
import Selenium
from Selenium.common.exceptions import NoSuchElementException
from Selenium.webdriver.common.keys import Keys
import time

patch = raw_input("Enter patch number\n")
rel = raw_input("Enter release\n")
plat = raw_input("Enter port\n")

browser = webdriver.Firefox()

browser.get("xxxxxxxxxxxxxxxxx")

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")

# Here I want to execute this javascript - "submitForm('patchCacheAdd',1,{'event':'ok'});return false"

browser.close()

Jika saya menggunakan -

Selenium.GetEval("submitForm('patchCacheAdd',1,{'event':'ok'});return false")

kesalahan keluar sebagai -

AttributeError: 'module' object has no attribute 'GetEval'I 
77
theharshest

Coba browser.execute_script alih-alih Selenium.GetEval.

Lihat jawaban ini misalnya.

111
Petr Viktorin

Gunakan execute_script, inilah contoh python:

from Selenium import webdriver
driver = webdriver.Firefox()
driver.get("http://stackoverflow.com/questions/7794087/running-javascript-in-Selenium-using-python") 
driver.execute_script("document.getElementsByClassName('comment-user')[0].click()")
48
Pedro Lobito

Jika Anda berpindah dari iframe, Anda mungkin tersesat di halaman Anda, cara terbaik untuk mengeksekusi beberapa jquery tanpa masalah (dengan selenium/python/gecko):

# 1) Get back to the main body page
driver.switch_to.default_content()

# 2) Download jquery lib file to your current folder manually & set path here
with open('./_lib/jquery-3.3.1.min.js', 'r') as jquery_js: 
    # 3) Read the jquery from a file
    jquery = jquery_js.read() 
    # 4) Load jquery lib
    driver.execute_script(jquery)
    # 5) Execute your command 
    driver.execute_script('$("#myId").click()')

Nikmati XD

5
Thomas LeBlond