user5653362 user5653362 - 1 month ago 6
Python Question

Creating new variables with Python with a loop

I have this piece of this code when I am running twice using selenium and python. After running this code twice I want to save values two different values into two different variables. For example CompanyId1 and CompanyId2. This is what I have tried so far but no luck

driver = webdriver.Chrome()
driver.maximize_window()
driver.get('https://cbbb.com/')
driver.find_element_by_id("email").clear()
driver.find_element_by_id("email").send_keys("")
driver.find_element_by_id("login-password").clear()
driver.find_element_by_id("login-password").send_keys("")
driver.find_element_by_css_selector("input.ButtonSm").click()
driver.find_element_by_class_name('navicon_nav').click()
driver.find_element_by_link_text("Ext Contacts").click()
iframe = driver.find_element_by_id('app_win')
driver.switch_to.frame(iframe)
driver.find_element_by_css_selector("i.fa.fa-plus").click()
driver.find_element_by_name("email").clear()
driver.find_element_by_name("email").send_keys("fakefake@sake.ca")
driver.find_element_by_css_selector("input.ButtonSm").click()
driver.find_element_by_css_selector("button.ButtonSm").click()
now = datetime.datetime.now()
now = now.strftime("%Y-%m-%d %H:%M:%S")
UserName = "TestUser" + now
driver.find_element_by_name("account").send_keys(UserName)
driver.find_element_by_css_selector("input.ButtonSm").click()
driver.find_element_by_css_selector("button.ButtonSm").click()
CompanyId[i]= driver.find_element_by_xpath("//th[label[contains(text(),'CompanyId')]]/following-sibling::td").text

Answer

Use a list:

companies = []

while whatever_condition:
   # your code here
   company_id = driver.find_element_by_xpath("//th[label[contains(text(),'CompanyId')]]/following-sibling::td").text  
   companies.append(company_id)