Skip to main content
 首页 » 编程设计

python之Selenium 脚本在打开新页面时找不到函数

2025年05月04日8cloudgamer

在单独的函数中打开另一个页面时,我的 selenium-python 脚本出现问题。

在函数 test2_points() 中,selenium 找不到 functionselect 和 Products_4。

这是我的脚本:

from selenium import selenium 
import unittest, time, re 
import socket 
import sys 
 
class discount_reward(unittest.TestCase): 
    def setUp(self): 
         print "setUp invoked" 
         self.port               = "4444" 
         self.ip_address         = "localhost" 
         self.browser            = "*chrome"#firefox 
         self.base_url           = "http://128.0.0.1:1062" 
         self.browser_title      = "Hammer" 
         self.verificationErrors = [] 
 
         try: 
            print "starting selenium with the following parameters:" 
            print "ip address:  %s\nport:  %s\nbrowser:  %s\nbase_url:  %s" %(self.ip_address, self.port, self.browser, self.base_url) 
            self.selenium = selenium(self.ip_address, self.port, self.browser, self.base_url) 
            self.selenium.start() 
 
         except socket.error, error: 
            print "\nSocket Exception: %s" %(error) 
            print "\nCould not connect to %s:%s with browser %s" %(self.base_url, self.port, self.browser) 
            sys.exit(1) 
 
    def test1_discount_reward(self): 
        sel = self.selenium 
        sel.open("/Hammer/offer-rew-discount.aspx?") 
        sel.select("functionselect", "label=Products_2") 
        sel.click("select1") 
    def test2_points_reward(self): 
        sel = self.selenium 
        sel.open("/Hammer/offer-rew-points.aspx?") 
        sel.select("functionselect", "label=Products_4") 
        sel.click("select1") 
 
    def tearDown(self): 
        self.selenium.stop() 
        self.assertEqual([], self.verificationErrors) 
 
if __name__ == "__main__": 
    unittest.main() 

谁能告诉我哪里出了问题?

请您参考如下方法:

您几乎肯定会在页面加载完成之前执行 sel.select()。任何时候您执行导致页面转换的操作(例如、open()、click() 链接或按钮),您应该在它后面加上 wait_for_page_to_load(timeout_in_milliseconds)。当页面完全加载到浏览器中时,等待将结束,或者超时(这显然是一种错误情况)。