使用Python在Selenium中运行javascript
我对Selenium完全陌生。我想在以下代码中执行一个javascript代码段(如代码中所注释),但是无法执行。请帮忙。
from selenium import webdriverimport 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
回答:
尝试browser.execute_script
代替selenium.GetEval
。
要返回值,只需return
在传递给execute_script()
方法的字符串中使用JavaScript关键字,例如
>>> from selenium import webdriver>>> wd = webdriver.Firefox()
>>> wd.get("http://localhost/foo/bar")
>>> wd.execute_script("return 5")
5
>>> wd.execute_script("return true")
True
>>> wd.execute_script("return {foo: 'bar'}")
{u'foo': u'bar'}
>>> wd.execute_script("return foobar()")
u'eli'
以上是 使用Python在Selenium中运行javascript 的全部内容, 来源链接: utcz.com/qa/410568.html