我使用Selenium导航到带有登录名/密码的URL(即URL_1)并提供登录凭据。我已登录并且URL(即URL_2)已按预期更改。我不知道如何导航URL_2,因为驱动程序仍然引用了URL_1。
提前致谢。
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
user_name = 'xyz'
password = 'xyz'
def login_process():
driver = webdriver.Firefox()
driver.get("URL_1")
#successfully navigated to URL_1
elem = driver.find_element_by_name("username")
elem.clear()
elem.send_keys(user_name)
elem = driver.find_element_by_name("password")
elem.clear()
elem.send_keys(password)
driver.find_element_by_id("submit").click()
#successfully entered URL_2
def query():
HOW DO I CHANGE THE DRIVER TO URL_2?
#elem = driver.find_element_by_class_name(ticker_box) #this doesn't work, references URL_1 driver
#elem.clear()
#elem.send_keys('xyz')
答案 0 :(得分:1)
创建一个带有驱动程序实例的类作为实例变量,而不是具有独立的功能。然后,使用self.driver.get()
导航到其他网址:
class MyTest(object):
def __init__(self):
self.driver = webdriver.Firefox()
def login_process(self):
self.driver.get("URL_1")
#successfully navigated to URL_1
elem = self.driver.find_element_by_name("username")
elem.clear()
elem.send_keys(user_name)
elem = self.driver.find_element_by_name("password")
elem.clear()
elem.send_keys(password)
self.driver.find_element_by_id("submit").click()
#successfully entered URL_2
def query(self):
self.driver.get("URL2")
# do smth
test = MyTest()
test.login_process()
test.query()
答案 1 :(得分:0)
导航到新页面后,如果您想在新页面上做某事
newURl = driver.window_handles[0]
driver.switch_to.window(newURl)
完成此操作后,您可以在新的url中执行某些操作,而不会出现“没有此类元素异常”的情况。
答案 2 :(得分:-1)
首先,您可以将url变量指定为全局:
global url;
url = "firstURL"
在第一个函数结束时,您可以将变量的值更改为新URL:
url = driver.current_url
然后你可以在第二个函数的开头获取新的url:
driver.get(url)