Python Selenium 自动化测试:打开浏览器并搜索内蒙古开放大学
import os
import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
def check_browser():
#检查是否已经打开了浏览器
try:
options = Options()
options.add_experimental_option('debuggerAddress', '127.0.0.1:9527')
browser = webdriver.Chrome(options=options)
browser.execute_script('return true')
return True
except:
return False
#使用cmd命令打开一个浏览器
if __name__ == '__main__':
if not check_browser():
os.system(r'start chrome --remote-debugging-port=9527 --user-data-dir='D:\评阅用'')
#获取刚才打开的浏览器
options = Options()
options.add_experimental_option('debuggerAddress', '127.0.0.1:9527')
browser = webdriver.Chrome(options=options)
browser.get('https://menhu.pt.ouchn.cn/site/ouchnPc/index')
print(browser.title)
#定位到搜索框,输入关键字
search_box = browser.find_element_by_id('search')
search_box.send_keys('内蒙古开放大学')
#点击搜索按钮
search_button = browser.find_element_by_id('searchBtn')
search_button.click()
time.sleep(2) #等待搜索结果加载
#定位到搜索结果中的第一个链接,点击进入
search_result = browser.find_element_by_css_selector('.search-list .search-item a')
search_result.click()
print(browser.title)
本代码使用 Python Selenium 库实现自动化测试,具体步骤如下:
- 检查浏览器是否已打开: 使用
check_browser()函数检查是否存在已打开的 Chrome 浏览器,并连接到调试端口9527。 - 打开浏览器: 如果浏览器未打开,则使用
os.system()命令打开一个新的 Chrome 浏览器,并配置调试端口和用户数据目录。 - 获取浏览器实例: 使用
webdriver.Chrome()获取已打开的浏览器实例。 - 访问目标网页: 使用
browser.get()方法访问目标网站https://menhu.pt.ouchn.cn/site/ouchnPc/index。 - 定位搜索框并输入关键字: 使用
browser.find_element_by_id()定位搜索框元素,并使用send_keys()方法输入关键字“内蒙古开放大学”。 - 点击搜索按钮: 使用
browser.find_element_by_id()定位搜索按钮元素,并使用click()方法点击搜索按钮。 - 等待搜索结果加载: 使用
time.sleep()方法等待搜索结果加载。 - 定位并点击第一个搜索结果: 使用
browser.find_element_by_css_selector()定位第一个搜索结果链接,并使用click()方法点击进入。 - 打印当前页面的标题: 使用
print(browser.title)打印当前页面的标题。
本代码示例展示了如何使用 Python Selenium 实现简单的网页自动化测试,包括打开浏览器、定位元素、输入文本、点击操作等。用户可以根据需要修改代码以实现其他功能。
原文地址: https://www.cveoy.top/t/topic/fYqK 著作权归作者所有。请勿转载和采集!