python selenium的基本操作

我沒有系統的學習python的面向對象等方面的編程,所以這個代碼能不能運行我不清楚。

 

只要能學會相關用法即可

from selenium import webdriver
import unittest
import time

class GloryRoad(unittest.TestCase):
# 測試前的初始化工作
	@classmethod
	def setUpClass(cls):
		# cls.driver=webdriver.Chrome()
		options = webdriver.ChromeOptions()
		options.add_argument('–headless')
		cls.driver = webdriver.Chrome(options=options)

	# 1.訪問網站1,添加斷言
	def test_visiturl(self):
		visiturl = 'http://www.baidu.com'
		self.driver.get(visiturl)
		# assert '百度0'in self.driver.page_source
		# 斷言
		assert self.driver.title.find('百度') >= 0, '頁面標題不包含:百度'


	# 2打開兩個網站前進或者後退
	def test_visitur2(self):
		visiturl = 'http://www.baidu.com'
		visitur2 = 'http://www.so.com'
		self.driver.get(visiturl)
		self.driver.get(visitur2)
		self.driver.back()
		self.driver.forward()

	# 3刷新當前頁面
	def test_visitur3(self):
		visitur3 = 'http://www.sogou.com'
		self.driver.get(visitur3)
		self.driver.refresh()

	# 4瀏覽器窗口最大化
	def test_visitur4(self):
		visitur4 = 'http://www.sogou.com'
		self.driver.get(visitur4)
		self.driver.maximize_window()

	# 5獲取並設置當前窗口在屏幕上位置
	def test_visitur5(self):
		visitur5 = 'http://www.sogou.com'
		self.driver.get(visitur5)
		# 獲取當前窗口在屏幕上位置
		position = self.driver.get_window_position()
		print('橫座標:', position['x'])
		print('縱座標:', position['y'])
		# 設置當前窗口在屏幕上位置
		self.driver.set_window_position(x=400, y=200)
		print(self.driver.get_window_position())

	# 6獲取瀏覽器窗口大小,返回字典類型數據
	def test_visitur6(self):
		visitur6 = 'http://www.sogou.com'
		self.driver.get(visitur6)
		# 獲取當前窗口在屏幕上位置
		size_Dict = self.driver.get_window_size()
		print('當前瀏覽器的寬:', size_Dict['width'])
		print('當前瀏覽器的高:', size_Dict['height'])
		# 設置瀏覽器窗口的大小
		self.driver.set_window_size(width=400, height=200,windowHandle='current')
		print(self.driver.get_window_size())

	# 7獲取頁面的title屬性值
	def test_visitur7(self):
		visitur7 = 'http://www.baidu.com'
		self.driver.get(visitur7)
		current_web_title = self.driver.title
		print('當前網頁的title屬性值爲:', current_web_title)
		#斷言頁面的title屬性是否是“百度一下,你就知道”
		self.assertEqual(current_web_title,"百度一下,你就知道","頁面title屬性錯誤!")

	#8獲取頁面HTML源代碼
	def test_visitur8(self):
		visitur8 = 'http://www.baidu.com'
		self.driver.get(visitur8)
		pagesource = self.driver.page_source
		# print('當前網頁的源碼爲:', pagesource)
		#斷言頁面源碼是否是包含“新聞”關鍵字,以此判斷頁面內容正確性
		self.assertTrue("新聞" in pagesource,"頁面源碼未找到'新聞'關鍵字")

	#9獲取當前頁面的URL地址
	def test_visitur9(self):
		visitur9 = 'http://www.baidu.com'
		self.driver.get(visitur9)
		currentpageurl = self.driver.current_url
		print('當前網頁的URL爲:', currentpageurl)
		#斷言當前頁面網址是否爲https://www.baidu.com/
		self.assertEqual(currentpageurl, "https://www.baidu.com/", "當前網址非預期網址!")

	# 10獲取當前頁面的元素基本信息
	def test_visitur10(self):
		visitur10 = 'http://www.baidu.com'
		self.driver.get(visitur10)
		# 查找百度首頁上的"新聞"鏈接元素
		newsElement = self.driver.find_element_by_xpath("//a[text()='新聞']")
		# 獲取査找到的"新聞”鏈接元素的基本信息
		print("元素的標籤名:", newsElement.tag_name)
		print("元素的 size:", newsElement.size)

	# 11獲取當前頁面的元素文本內容
	def test_visitur11(self):
		visitur11 = 'http://www.baidu.com'
		self.driver.get(visitur11)
		import time
		time.sleep(3)
		# 通過xpath定位方式找到id屬性值爲"ul"的div元素下的第一個鏈接元素
		aElement = self.driver.find_element_by_xpath("//*[@class='mnav'][1]")
		# 通過找到的鏈接元素對象的text屬性獲取到鏈接元素的文本內容
		a_text = aElement.text
		self.assertEqual(a_text, "新聞")

	#12判斷頁面元素是否可見
	def test_getWebElementIsDisplayed12(self):
		import os
		url12 = 'file:///' + os.path.abspath('A_12.html')
		# 訪問自定義的HTML網頁
		self.driver.get(url12)
		# 通過"div2"找到第二個div元素
		div2 = self.driver.find_element_by_id("div2")
		# 判斷第二個div元素是否在頁面上可見
		print(div2.is_displayed())
		# 單擊第一個切換div按鈕,將第二個div顯示在頁面上
		self.driver.find_element_by_id("button1").click()
		# 再次判斷第二個div元素是否可見
		print(div2.is_displayed())
		# 通過id="div4"找到第四個div元素
		div4 = self.driver.find_element_by_id("div4")
		# 判斷第四個div元素是否在頁面上可見
		print(div4.is_displayed())
		# 單擊第二個切換div按鈕,將第四個div顯示在頁面上
		self.driver.find_element_by_id("button2").click()
		# 再次判斷第四個div元素是否可見
		print(div4.is_displayed())

	#13判斷頁面元素是否可操作
	def test_getWebElementIsEnablec13(self):
		import os
		url13 = 'file:///' + os.path.abspath('A_13.html')
		# 訪問自定義的HTML網頁
		self.driver.get(url13)
		# 通過id找到第一個input元素
		input1 = self.driver.find_element_by_id("input1")
		# 判斷第一個input元素是否可操作
		print(input1.is_enabled())
		# 通過id找到第二個:input元素
		input2 = self.driver.find_element_by_id("input2")
		# 判斷第二個input元素是否可操作
		print(input2.is_enabled())
		# 通過id找到第三個input元素
		input3 = self.driver.find_element_by_id("input3")
		# 判斷第三個input元素是否可操作
		print(input3.is_enabled())

	#14獲取頁面元素的屬性
	def test_getWebElementAttribute14(self):
		url = "http://www.sogou.com"
		# 訪問sogou首頁
		self.driver.get(url)
		# 找到搜索輸入框元素
		searchBox = self.driver.find_element_by_id("query")
		# 獲取搜索輸入框頁面元素的name屬性值
		print(searchBox.get_attribute("name"))
		# 向搜索輸入框中輸入"Selinum3"內容
		searchBox.send_keys("Selinum3")
		# 獲取頁面搜索框的value屬性值(即搜索輸入框的文字內容)
		print(searchBox.get_attribute("value"))

	#15獲取頁面元素的CSS屬性值
	def test_getWebElementAttribute15(self):
		url = "http://www.baidu.com"
		# 訪問百度首頁
		self.driver.get(url)
		# 找到搜索輸入框元素
		searchBox = self.driver.find_element_by_id("kw")
		# 使用頁面元素對象的value_of_css_property()方法獲取元素的CSS屬性值
		print("搜索輸入框的高度是:", searchBox.value_of_css_property("height"))
		print("搜索輸入框的寬度是:", searchBox.value_of_css_property("width"))
		font = searchBox.value_of_css_property("font-family")
		print("搜索輸入框的字體是:", font)
		# 斷言搜索輸入框的字體是否是arial字體
		self.assertEqual(font, "arial")

	#16.清空輸入框中的內容
	def test_clearInputBoxText16(self):
		url = "http://www.baidu.com"
		# 訪問百度網頁
		self.driver.get(url)
		# 獲取輸入框頁面對象
		input = self.driver.find_element_by_id("kw")
		input.send_keys("selenium")
		import time
		time.sleep(3)
		# 清除輸人框中默認內容
		input.clear()
		# 等待3秒,主要看清空輸入框內容後的效果
		time.sleep(3)

	#17在輸入框中輸入指定內容
	def test_sendTextToInputBoxText17(self):
		import os
		# url = "d:\\test.html"
		url = 'file:///' + os.path.abspath('a_17.html')
		# 訪問自定義的HTML網頁
		self.driver.get(url)
		# 獲取輸入框頁面對象
		input = self.driver.find_element_by_id("text")
		# 清除輸入框中默認內容
		input.clear()
		input.send_keys(u"我是輸入的文本內容")
		# 導入time包
		import time
		# 等待3秒,主要看清空輸入框內容後的效果
		time.sleep(3)

	# 18單擊按鈕
	def test_clickButton18(self):
		import os
		# url = "d:\\test.html"
		url = 'file:///' + os.path.abspath('A_18.html')
		# 訪問自定義的HTML網頁
		self.driver.get(url)
		# 獲取按鈕頁面對象
		button = self.driver.find_element_by_id("button")
		# 模擬鼠標左鍵單擊操作
		button.click()
		import time
		time.sleep(3)
		
	#19雙擊某個元素
	def test_doubleClick19(self):
		import os
		# url = "d:\\test.html"
		url = 'file:///' + os.path.abspath('A_19.html')
		# 訪問自定義的HTML網頁
		self.driver.get(url)
		# 獲取頁面輸入元素
		inputBox = self.driver.find_element_by_id("inputBox")
		# 導入支持雙擊操作的模塊
		from selenium.webdriver import ActionChains
		# 開始模擬鼠標雙擊操作
		action_chains = ActionChains(self.driver)
		action_chains.double_click(inputBox).perform()
		import time
		time.sleep(3)
		# 執行後雙擊input框,背景顏色將變爲紅色

	# 20操作單選下拉列表
	def test_printSelectText20(self):
		import os
		url = 'file:///' + os.path.abspath('A_20.html')
		# 訪問自定義的HTML網頁
		self.driver.get(url)
		# 使用name屬性找到頁面上name屬性爲"fruit”的下拉列表元素
		select = self.driver.find_element_by_name("fruit")
		all_options = select.find_elements_by_tag_name("option")
		for option in all_options:
			print("選項顯示的文本:", option.text)
			print("選項值爲:", option.get_attribute("value"))
			option.click()
			time.sleep(1)
		#20操作單選下拉列表(2)
		from selenium.webdriver.common.action_chains import ActionChains
		self.driver.get('http://www.baidu.com')
		setting = self.driver.find_element_by_link_text('設置')
		ActionChains(self.driver).move_to_element(setting).perform()  # 需要加.perform() 執行一下
		self.driver.find_element_by_link_text('高級搜索').click()
		self.driver.find_elements_by_class_name('c-input')
		time.sleep(2)
		# 導入Select包
		from selenium.webdriver.support.ui import Select
		ft = self.driver.find_element_by_name('ft')
		# 實例化一個select對象
		ft_list = Select(ft)
		print(type(ft), type(ft_list))
		ft_list.select_by_value('rtf')  # 通過value選擇
		ft_list.select_by_index(1)  # 通過索引選擇
		ft_list.select_by_visible_text('所有格式')  # 文本

	#21斷言單選列表選項值
	def test_visitURL21(self):
		import os
		url='file:///'+os.path.abspath('A_20.html')
		self.driver.get(url)
		#導入select模塊
		from selenium.webdriver.support.ui import Select
		select_element=Select(self.driver.find_element_by_xpath('/html/body/select'))
		#獲取所有選項的頁面元素對象
		actual_options=select_element.options
		except_optionslist=['桃子','西瓜','橘子','獼猴桃','山楂','荔枝']
		actual_options_list=list(map(lambda option:option.text,actual_options))
		self.assertListEqual(except_optionslist,actual_options_list)
		
	#22操作多選的選擇列表
	def test_operateMultipleOptionDropList22(self):
		import os
		url = 'file:///' + os.path.abspath('A_22.html')
		# 訪問自定義的HTML網頁
		self.driver.get(url)
		# 導入Select模塊
		from selenium.webdriver.support.ui import Select
		import time
		# 使用xpath定位方式獲取select頁面元素對象
		select_element = Select(self.driver.find_element_by_xpath("//select"))
		# 通過序號選擇第一個元素
		select_element.select_by_index(0)
		# 通過選項的文本選擇"山楂"選項
		select_element.select_by_visible_text("山楂")
		# 通過選項的value屬性值選擇value = "mihoutao"的選項
		select_element.select_by_value("mihoutao")
		# 打印所有的選中項文本
		for option in select_element.all_selected_options:
			print(option.text)
		# 取消所有已選中項
		select_element.deselect_all()
		time.sleep(2)
		print("------再次選中3個選項------")
		#用索引定位元素
		select_element.select_by_index(1)
		# 用文本定位元素
		select_element.select_by_visible_text("荔枝")
		#用value值定位元素
		select_element.select_by_value("juzi")
		# 通過選項文本取消已選中的文本爲"荔枝"選項
		select_element.deselect_by_visible_text("荔枝")
		# 通過序號取消已選中的序號爲1的選項
		select_element.deselect_by_index(1)
		# 通過選項的value屬性值取消已選中的value = "juzi"的選項
		select_element.deselect_by_value("juzi")
	# 23操作可以輸入的下拉列表(輸入的同時模擬按鍵)
	def test_operateMultipleOptionDropList23(self):
		import os
		url = 'file:///' + os.path.abspath('A_23.html')
		self.driver.get(url)
		# 導入模擬鍵盤模塊
		from selenium.webdriver.common.keys import Keys
		self.driver.find_element_by_id("select").clear()
		import time
		time.sleep(1)
		# 輸入的同時按下箭頭鍵
		self.driver.find_element_by_id("select").send_keys("c", Keys.ARROW_DOWN)
		self.driver.find_element_by_id("select").send_keys(Keys.ARROW_DOWN)
		self.driver.find_element_by_id("select").send_keys(Keys.ENTER)
		time.sleep(3)
	#24操作單選框,is_selected判斷元素是否被選中
	def test_operateRadio24(self):
		import os
		url = 'file:///' + os.path.abspath('A_24.html')
		# 訪問自定義的HTML網頁
		self.driver.get(url)
		# 使用xpath定位獲取value屬性值爲'berry'的input元素對象,也就是"草莓"選項
		berryRadio = self.driver.find_element_by_xpath("//input[@value = 'berry']")
		# 單擊選擇"草莓"選項
		berryRadio.click()
		# 斷言"草莓”單選框被成功選中
		self.assertTrue(berryRadio.is_selected(), "草莓單選框未被選中!")
		if berryRadio.is_selected():
			# 如果"草莓"單選框被成功選中,重新選擇n西瓜"選項
			watermelonRadio = self.driver.find_element_by_xpath("//input[@value ='watermelon']")
			watermelonRadio.click()
			# 選擇"西瓜"選項以後,斷言"草莓"選項處於未被選中狀態
			self.assertFalse(berryRadio.is_selected())
		# 査找所有name屬性值爲"fruit"的單選框元素對象,並存放在radioList列表中
		radioList = self.driver.find_elements_by_xpath("//input[ @narae='fruit']")
		'''
		循環遍歷radioList中的每個單選按鈕,查找value屬性值爲"orange"的單選框,
		如果找到此單選框以後,發現未處於選中狀態,則調用click方法選中該選項.'''
		for radio in radioList:
			if radio.get_attribute("value") == "orange":
				if not radio.is_selected():
					radio.click()
					self.assertEqual(radio.get_attribute("value"), "orange")
	#25.操作複選框
	def test_operateCheckBox25(self):
		import os
		url = 'file:///' + os.path.abspath('A_25.html')
		self.driver.get(url)
		# 使用xpath定位獲取value屬性值爲'berry'的input元素對象,也就是"草莓"選項
		berryCheckBox = self.driver.find_element_by_xpath("//input[@value = 'berry' ]")
		# 單擊選擇"草莓"選項
		berryCheckBox.click()
		# 斷言"草莓"複選框被成功選中
		self.assertTrue(berryCheckBox.is_selected(), u"草莓複選框未被選中!")
		if berryCheckBox.is_selected():
			# 如果"草莓"複選框被成功選中,再次單擊取消選中
			berryCheckBox.click()
			# 斷言"草莓"複選框處於未選中狀態
			self.assertFalse(berryCheckBox.is_selected())
		# 査找所有name屬性值爲"fruit"的複選框元素對象,並存放在checkBoxList列表中
		checkBoxList = self.driver.find_elements_by_xpath("//input[@name = 'fruit']")
		# 遍歷checkBoUst列表中的所有複選框元素,讓全部複選框處於被選中狀態
		for box in checkBoxList:
			if not box.is_selected():
				box.click()
	# 26.斷言頁面源碼中的關鍵字
	def test_assertKeyWord26(self):
		url = "http://www.baidu.com"
		# 訪問百度首頁
		self.driver.get(url)
		self.driver.find_element_by_id("kw").send_keys(u"selenium")
		self.driver.find_element_by_id("su").click()
		import time
		time.sleep(4)
		# 通過斷言頁面是否存在某些關鍵字來確定頁面按照預期加載
		assert "selenium" in self.driver.page_source, u"頁面源碼中不存在該關鍵字!"
	#27對當前瀏覽器窗口截屏
	def test_captureScreenInCurrentWindow27(self):
		url = "http://www.sogou.com"
		# 訪問搜狗首頁
		self.driver.get(url)
		try:
			'''
			調用get_screenshot_as_f ile(filename)方法,對瀏覽器當前打開頁面
			進行截圖,並保爲C盤下的screenPicture.png文件
			'''
			result = self.driver.get_screenshot_as_file(r"C:\Users\Administrator\PycharmProjects\untitled58\screenPicture.png")
			print(result)
		except IOError as e:
			print(e)
	#28.模擬鍵盤單個按鍵操作
	def test_simulateASingleKeys28(self):
		from selenium.webdriver.common.keys import Keys
		url = "http://www.sogou.com"
		self.driver.get(url)
		query = self.driver.find_element_by_id("query")
		query.send_keys(Keys.F12)
		time.sleep(3)
		query.send_keys(Keys.F12)
		query.send_keys("selenium3")
		query.send_keys(Keys.ENTER)
		time.sleep(3)
	#29.模擬組合按鍵操作
	def test_simulationCombinationKeys29(self):
		url = "http://www.baidu.com"
		# 訪問百度首頁
		self.driver.get(url)
		# 將焦點切換到搜索輸人框中
		input = self.driver.find_element_by_id("kw")
		input.click()
		input.send_keys(u"Selenium3")
		time.sleep(2)
		from selenium.webdriver import ActionChains
		from selenium.webdriver.common.keys import Keys
		ActionChains(self.driver).key_down(Keys.CONTROL).send_keys('a'). \
			key_up(Keys.CONTROL).perform()
		time.sleep(2)
		ActionChains(self.driver).key_down(Keys.CONTROL).send_keys('x'). \
			key_up(Keys.CONTROL).perform()
		self.driver.get(url)
		self.driver.find_element_by_id("kw").click()
		# 模擬Ctrl + V組合鍵,將從剪貼板中獲取到的內容粘貼到搜索輸入框中
		ActionChains(self.driver).key_down(Keys.CONTROL).send_keys('v'). \
			key_up(Keys.CONTROL).perform()
		# 單擊"百度一下"搜索按鈕
		self.driver.find_element_by_id("su").click()
		time.sleep(3)
	# #30.模擬鼠標右鍵
	# from selenium.webdriver import ActionChains
	# from selenium.webdriver.common.keys import Keys
	# import time
	# import win32clipboard as w
	# import win32con
	# def setText(aString):
	#     w.OpenClipboard()
	#     w.EmptyClipboard()
	#     w.SetClipboardData(win32con.CF_UNICODETEXT, aString)
	#     w.CloseClipboard()
	# def test_rigthClickMouse(self):
	#     url = "http://www.sogou.com"
	#     # 訪問搜狗首頁
	#     self.driver.get(url)
	#     # 找到搜索輸人框
	#     searchBox = self.driver.find_element_by_id("query")
	#     # 將焦點切換到搜索輸入框
	#     searchBox.click()
	#     time.sleep(2)
	#     # 在搜索輸入框上執行一個鼠標右鍵單擊操作
	#     ActionChains(self.driver).context_click(searchBox).perform()
	#     # 將"gloryroad"數據設置到剪貼板中,相當於執行了複製操作
	#     setText(u'gloryroad')
	#     # 發送一個粘貼命令,字符P指代粘貼操作
	#     ActionChains(self.driver).send_keys('P').perform()
	#     # 單擊搜索按鈕
	#     self.driver.find_element_by_id('stb').click()
	#     time.sleep(2)
	#31模擬鼠標左鍵按下與釋放
	def test_simulationLeftClickMouseOfProcess31(self):
		import os
		url = 'file:///' + os.path.abspath('A_31.html')
		# 訪問自定義的HTML網頁
		self.driver.get(url)
		div = self.driver.find_element_by_id("div1")
		from selenium.webdriver import ActionChains
		import time
		# 在id屬性值爲"div1"的元素上執行按下鼠標左鍵,並保持
		ActionChains(self.driver).click_and_hold(div).perform()
		time.sleep(2)
		# 在id屬性值爲”div1”的元素上釋放一直按下的鼠標左鍵
		ActionChains(self.driver).release(div).perform()
		time.sleep(2)
		ActionChains(self.driver).click_and_hold(div).perform()
		time.sleep(2)
		ActionChains(self.driver).release(div).perform()
	#32保持鼠標懸停在某個元素上
	def test_roverOnElement32(self):
		import os
		url = 'file:///' + os.path.abspath('A_32.html')
		# 訪問自定義的HTML網頁
		self.driver.get(url)
		# 找到頁面上第一個鏈接元素
		link1 = self.driver.find_element_by_partial_link_text(u"鼠標指過來1")
		# 找到頁面上第二個鏈接元素
		link2 = self.driver.find_element_by_partial_link_text(u"鼠標指過來2")
		# 找到頁面上的p元素
		p = self.driver.find_element_by_xpath("//p")
		print(link1.text, link2.text)
		# 導入需要的Python包
		from selenium.webdriver import ActionChains
		import time
		# 將鼠標懸浮到第一個鏈接元素上
		ActionChains(self.driver).move_to_element(link1).perform()
		time.sleep(2)
		# 將鼠標從第一個鏈接元素移動到P元素上
		ActionChains(self.driver).move_to_element(p).perform()
		time.sleep(2)
		# 將鼠標懸浮到第二個鏈接元素上
		ActionChains(self.driver).move_to_element(link2).perform()
		time.sleep(2)
		# 將鼠標從第二個鏈接元素移動到P元素上
		ActionChains(self.driver).move_to_element(p).perform()
		time.sleep(2)
	#33.判斷頁面元素是否存在
	def isElementPresent(self, by, value):
		# 從 selenium.common.exceptions 模塊導入 NoSuchElementException 異常類
		from selenium.common.exceptions import NoSuchElementException
		try:
			element = self.driver.find_element(by=by, value=value)
		except NoSuchElementException as e:
			# 打印異常信息
			print(e)
			# 發生了 NoSuchElementException異常,說明頁面中未找到該元素,返回False
			return False
		else:
			# 沒有發生異常,表示在頁面中找到了該元素,返回True
			return True

	def test_isElementPresent33(self):
		url = "http://www.sogou.com"
		# 訪問sogou首頁
		self.driver.get(url)
		# 判斷頁面元素id屬性值爲"query"的頁面元素是否存在
		res = self.isElementPresent("id", "query")
		if res is True:
			print(u"所查找的元素存在於頁面上!")
		else:
			print(u"頁面中未找到所需要的頁面元素!")
	#34隱式等待implicitly_wait()
	def test_iraplictWait34(self):
		# 導入異常類
		from selenium.common.exceptions import NoSuchElementException, TimeoutException
		# 導入堆棧類
		import traceback
		url = "http://www.sogou.com"
		# 訪問sogou首頁
		self.driver.get(url)
		# 通過driver對象impUcitly_wait()方法來設置隱式等待時間,最長等待10秒
		self.driver.implicitly_wait(10)
		try:
			# 査找sogou首頁的搜索輸人框頁面元素
			searchBox = self.driver.find_element_by_id("query")
			# 在搜索輸人框中輸入"selenium3"
			searchBox.send_keys(u"selenium3")
			# 査找sogou首頁搜索按鈕頁面元素
			click = self.driver.find_element_by_id("stb")
			# 單擊搜索按鈕
			click.click()
		except (NoSuchElementException, TimeoutException) as e:
			# 打印異常的堆棧信息
			traceback.print_exc()
	#35顯示等待WebDriverWait()
	def test_explicitWait35(self):
		# 導入堆棧類
		import traceback
		# 導入By類
		from selenium.webdriver.common.by import By
		# 導入顯式等待類
		from selenium.webdriver.support.ui import WebDriverWait
		# 導入期望場景類
		from selenium.webdriver.support import expected_conditions as EC
		from selenium.common.exceptions import TimeoutException, NoSuchElementException
		import os
		url = 'file:///' + os.path.abspath('A_35.html')
		# 訪問自定義的HTML網頁
		self.driver.get(url)
		try:
			wait = WebDriverWait(self.driver, 10, 0.2)
			wait.until(EC.title_is(u"你喜歡的水果"))
			print(u"網頁標題是'你喜歡的水果'")
			# 等待10秒,直到要找的按鈕出現
			element = WebDriverWait(self.driver, 10).until \
				(lambda x: x.find_element_by_xpath \
					("//input[@value = 'Display alert box']"))
			element.click()
			# 等待alert框出現
			alert = wait.until(EC.alert_is_present())
			# 打印alert框體消息
			print(alert.text)
			# 確認警告信息
			alert.accept()
			# 獲取id屬性值爲"peach"的頁面元素
			peach = self.driver.find_element_by_id("peach")
			# 判斷id屬性值爲"peach"的頁面元素是否能被選中
			peachElement = wait.until(EC.element_to_be_selected(peach))
			print(u"下拉列表的選項'桃子'目前處於選中狀態")
			# 判斷複選框是否可見並且能被單擊
			wait.until(EC.element_to_be_clickable((By.ID, 'check')))
			print("複選框可見並且能被單擊")
		except TimeoutException as e:
			# 捕獲 TimeoutException 異常
			print(traceback.print_exc())
		except NoSuchElementException as e:
			# 捕獲 NoSuchElementException 異常
			print(traceback.print_exc())
		except Exception as e:
			# 捕獲其他異常
			print(traceback.print_exc())


	@classmethod
	def tearDownClass(cls):
		cls.driver.quit()

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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章