from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import WebDriverException
from selenium.webdriver.common.keys import Keys
import unittest
import traceback
from time import sleep
# 封装加亮当前操作元素的函数
def heighLightElement(driver,element):
driver.execute_script("arguments[0].setAttribute('style',arguments[1]);",element,"background:green;border:2px solid red;")
class TestAjax(unittest.TestCase):
def setUp(self):
self.driver=webdriver.Firefox()
#
def test_AjaxArrowDown(self):
url = "http://www.sogou.com/"
self.driver.get(url)
searchBox = self.driver.find_element_by_id('query')
# 加量搜索框
heighLightElement(self.driver,searchBox)
searchBox.send_keys('光荣之路')
sleep(2)
# 方法一:通过模拟键盘下箭头进行悬浮框内容选择
for i in range(3):
searchBox.send_keys(Keys.DOWN)
sleep(1)
# 输入回车键进行搜索
searchBox.send_keys(Keys.ENTER)
sleep(1)
# 方法二:使用xpath固定选择第三个选项
# suggest_option = self.driver.find_element_by_xpath('/html/body/div[3]/div[2]/div[4]/div/div[1]/ul/li[3]')
# suggest_option.click()
# 方法二:通过匹配模糊内容进行悬浮框内容选择
def test_AjaxOptionByWord(self):
url = "http://www.sogou.com/"
try:
self.driver.get(url)
searchBox = self.driver.find_element_by_id('query')
# 加亮搜索框
heighLightElement(self.driver,searchBox)
searchBox.send_keys('光荣之路')
sleep(2)
# 获得所有的联想关键词底的列表
suggest_options = self.driver.find_elements_by_xpath("/html/body/div[3]/div[2]/div[4]/div/div[1]/ul/li")
# 从联想关键词列表中找到包含“电影”关键词的选项
for suggest_option in suggest_options:
# print(suggest_option.text)
if '电影' in suggest_option.text:
suggest_option.click()
sleep(2)
break
except NoSuchElementException:
print(traceback.print_exc())
except WebDriverException:
print(traceback.print_exc())
def tearDown(self):
self.driver.quit()
if __name__ == '__main__':
unittest.main()