Selenium Python webdriver:driver.get() 不接受变量?

1 投票
2 回答
8247 浏览
提问于 2025-04-18 01:01

我正在尝试写一个自动化测试脚本,这个脚本可以对多个网址执行一系列操作。我之所以想这么做,是因为我在测试一个有多个前端界面的网页应用,而这些界面的功能完全一样。所以如果我能用一个测试脚本来跑遍所有的界面,确保基本功能正常,这样在代码更新后进行回归测试时就能省下很多时间。

我现在的代码如下:

# initialize the unittest framework
import unittest
# initialize the selenium framework and grab the toolbox for keyboard output
from selenium import selenium, webdriver
# prepare for the usage of remote browsers
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

class Clubmodule(unittest.TestCase):
    def setUp(self):
    #   load up the remote driver and tell it to use Firefox
        self.driver = webdriver.Remote(
        command_executor="http://127.0.0.1:4444/wd/hub",    
        desired_capabilities=DesiredCapabilities.FIREFOX)
        self.driver.implicitly_wait(3)

    def test_010_LoginAdmin(self):
        driver = self.driver
    #   prepare the URL by loading the list from a textfile
        with open('urllist.txt', 'r') as f:
            urllist = [line.strip() for line in f]
    #   Go to the /admin url
        for url in urllist:
        #   create the testurl  
            testurl = str(url) + str("/admin")
        #   go to the testurl
            driver.get("%s" %testurl)
        #   log in using the admin credentials

    def tearDown(self):
    #   close the browser
        self.driver.close()

# make it so!
if __name__ == "__main__":
    unittest.main()

当我打印变量 testurl 的时候,得到的结果是正确的功能。但是当我用Python运行我的脚本时,似乎没有把 driver.get("%s" %testurl) 转换成 driver.get("actualurl")

我希望这只是语法问题,但我尝试了所有我能想到的变体后,开始觉得这可能是Webdriver的一个限制。请问这真的能做到吗?

2 个回答

0

我开始觉得这可能是Webdriver的一个限制。

绝对不是。

下面的代码在我这里用Selenium 2.44运行得很好:

from selenium import webdriver

testurl = 'http://example.com'
driver = webdriver.Firefox()
driver.get('%s' % testurl)
7

这样怎么样呢

driver.get(testurl)

我觉得不需要用字符串插值。

撰写回答