from selenium import webdriver
import unittest,time,re
from selenium.webdriver.common.keys import Keys

'''
元交网登录退出
'''

username=''
password=''


class Untitled(unittest.TestCase):
def setUp(self):
# 打开网址
self.driver=webdriver.Firefox()
self.driver.implicitly_wait(10)
self.url="https://ca.cecb2b.com/login"
self.driver.maximize_window()

def shop_buy(self):
driver=self.driver
driver.get(self.url)
# 登录
driver.find_element_by_xpath("//input[@id='username']").clear()
driver.find_element_by_xpath("//input[@id='username']").send_keys(username)
self.driver.implicitly_wait(10)
driver.find_element_by_xpath("//input[@class='text_inps1 text_inps2']").send_keys(password)
driver.find_element_by_xpath("//input[@type='submit']").click()
driver.find_element_by_xpath("//a[contains(text(),'元器件交易网-全球领先电子配套平台')]").click() #元交网首页

now_handle=driver.current_window_handle #获取当前窗口句柄
print("----now handle id first is %s"%now_handle)

# 购买某产品
driver.find_element_by_xpath("//*[@class='buy-now']").find_element_by_link_text('立即购买').click()
# driver.implicitly_wait(10)
time.sleep(2)

all_handles = self.driver.window_handles #获取所有窗口的句柄
# 将所有窗口id遍历一遍,将最新的写入到txt中
filename='write_data.txt'
with open(filename, 'w') as f:
for i in range(len(all_handles)):
f.write(str(all_handles[i]+"\n"))

time.sleep(2) #增加延迟,以确保浏览器响应
# print("---新页面id is %s 旧页面id is %s"%(all_handles[1],now_handle))

# 进入购物车
driver.switch_to_window(all_handles[-1])
time.sleep(1)
driver.find_element_by_xpath("//div[@class='gauge']/a[1]").click()
time.sleep(1)
# print(now_handle)

# 进入结算
time.sleep(2)
self.driver.find_element_by_xpath("//input[@id='inlandAllTop']").click() # 复选框checkbox
time.sleep(2)
self.driver.find_element_by_xpath("//div[@class='company-list']/input[1]").send_keys(Keys.SPACE) #选择第一个checkbox
if driver.find_element_by_xpath("//div[@class='company-list']/input[1]").is_selected():
print('selected!')
else:
print('not yet!')
time.sleep(1)
self.driver.find_element_by_xpath("//a[@class='accounts']").click()
time.sleep(2)

self.driver.find_element_by_link_text("提交订单").click()
time.sleep(2)
self.driver.find_element_by_link_text("国内交货支付").click()

def tearDown(self):
self.driver.quit()

if __name__ == '__main__':
unittest.main()