在Ajax方式产生的浮动框中,单击选择包含某个关键字的选项

 目的:

有些被测试也你按包好Ajax的局部刷新机制,并且会产生显示多条数据的浮动框,需要单机选择浮动框中包含某个关键字的选项

测试网址:

http://www.sogou.com

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


class TestDemo(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Chrome()

    def test_execut(self):
        url = "https://www.sogou.com/"

        self.driver.get(url)

        # 找到输入框
        searchBox = self.driver.find_element_by_id("query")
        time.sleep(2)
        # 在输入框输入内容
        searchBox.send_keys("河北")

        time.sleep(2)

        # 你想点击第几个输入框的内容 就循环几次
        for i in range(3):
            searchBox.send_keys(Keys.DOWN)
            time.sleep(1)
        searchBox.send_keys(Keys.ENTER)
        time.sleep(3)

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


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

 

 方法二 通过匹配模糊内容选择悬浮框中的选项

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
import unittest
import traceback
import time


class TestDemo(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Chrome()

    def test_execut(self):
        url = "https://www.sogou.com/"

        self.driver.get(url)
        try:
            searchBox = self.driver.find_element_by_id("query")
            searchBox.send_keys("河北")

            time.sleep(2)

            suggetion_option = self.driver.find_element_by_xpath("//ul/li[contains(.,'疫情')]")
            time.sleep(3)
            suggetion_option.click()
            time.sleep(5)
        except NoSuchElementException as e:
            # 打印异常堆栈信息
            print(traceback.print_exc())

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


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

  

还有一种情况:就是在ajax弹出框里我们的内容是经常改变的,但是我们就是想打开第三个搜索结果的 就将第二个里面的 xpath 改一下

suggetion_option = self.driver.find_element_by_xpath("//*[@id='vl']/div[1]/ul/li[4]")

 

  

 
posted @ 2021-01-23 13:33  流年中渲染了微笑  阅读(98)  评论(0编辑  收藏  举报