Ajax浮动框选择关键字选项

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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值