使用Python在Selenium中运行JavaScript

112

我完全不懂Selenium。我想在下面的代码中执行一个JavaScript片段(如代码中所述),但无法实现。请帮忙。

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

如果我使用 -

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

它报错为 -

AttributeError: 'module' object has no attribute 'GetEval'I 
3个回答

144

尝试使用browser.execute_script代替selenium.GetEval

参考这个答案


78

您可以使用execute_script,以下是Python示例:

from selenium import webdriver
driver = webdriver.Firefox()
driver.get("https://dev59.com/sGsz5IYBdhLWcg3wlY69") 
driver.execute_script("document.getElementsByClassName('comment-user')[0].click()")

上面的代码是为了测试而添加的注释。 - Pedro Lobito

8
如果你从iframes中移动,你可能会在页面中迷失方向。最好的方法是使用selenimum/python/gecko执行一些jquery而不出现问题:
# 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()')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接