专栏导读


-
🌸 欢迎来到Python办公自动化专栏—Python处理办公问题,解放您的双手
-
-
-
-
📕 此外还有python基础专栏:请点击——>Python基础学习专栏求订阅
-
文章作者技术和水平有限,如果文中出现错误,希望大家能指正🙏
-
❤️ 欢迎各位佬关注! ❤️
1、库的介绍
Selenium 是一个强大的工具,用于自动化Web应用程序的测试。它支持多种编程语言(如Python、Java、C#等)来编写测试脚本,并且可以与各种浏览器(如Chrome、Firefox、Edge等)进行交互。Selenium 主要由以下几个部分组成:
-
①:Selenium WebDriver:
这是 Selenium 最新的核心组件,提供了一个简洁、直观的接口来控制浏览器。WebDriver 可以模拟真实用户的操作,比如点击按钮、填写表单、导航到页面等。它直接与浏览器进行通信,因此能够提供更接近真实用户行为的测试环境。
-
②:Selenium Grid
Selenium Grid 允许将测试分布在多台机器上运行,从而加快测试执行的速度。通过 Grid,你可以同时在不同的操作系统和浏览器配置中并行地运行测试用例,这对于需要跨平台测试的应用非常有用。
-
③:Selenium IDE:
Selenium IDE 是一个用于录制和回放测试用例的工具,最初作为 Firefox 浏览器的一个插件发布,后来也推出了适用于 Chrome 的版本。它非常适合初学者使用,因为不需要编写代码即可创建测试用例。
-
④:Selenium RC (Remote Control):
这是 Selenium 的早期版本,现在已经被 Selenium WebDriver 所取代。RC 通过一个服务器端的 Java 应用来接收来自客户端脚本的命令,并将其转发给浏览器。尽管 RC 已经不再推荐使用,但仍然可以在某些特定场景下找到它的身影。
使用场景
-
①:自动化测试:
Selenium 最常见的用途就是自动化Web应用的测试过程。开发者或测试工程师可以利用 Selenium 编写自动化测试脚本来验证网站的功能是否按预期工作。
-
②:数据抓取:
虽然 Selenium 不是专门的数据抓取工具,但由于它可以完全控制浏览器的行为,因此也被广泛应用于需要登录、JavaScript 渲染等复杂交互的数据抓取任务中。
-
③:界面测试:
Selenium 能够帮助确保网页在不同浏览器上的显示效果一致,以及检查布局、颜色等视觉元素是否符合设计要求。
2、库的安装
| 库 | 用途 | 安装 |
|---|
| selenium | 控制浏览器 | pip install selenium -i https://pypi.tuna.tsinghua.edu.cn/simple/ |
| os | 获取绝对路径 | 内置库无需安装 |
3、核心代码
-
①:启动 Chrome 并开启远程调试端口(例如9222)
略,在下面
略,请参考以往文章
| 文章 | 链接 |
|---|
| Python爬虫实战(实战篇)—19—selenium获取柯南所有剧集写入Excel—附完整版代码) | 点我进入本文 |
| python+selenium判断【加载中】元素在就一直等待不在就点击下载(非常好用) | 点我进入本文 |
| Python+selenium+PIL实现网页自动截图 | 点我进入本文 |
| Python控制selenium之谷歌驱动器移动至隐藏元素上 | 点我进入本文 |
| python-selenium控制浏览器多开窗口 | 点我进入本文 |
| python+selenium模拟键盘使用ESC退出某个页面中的小页面 | 点我进入本文 |
4、完整1:自动打开本地谷歌浏览器
-
启动Chrome并开启远程调试
-
启动 Chrome 并开启远程调试端口(例如9222),如你已经配置好的:
'''
@Project :测试
@File :自动打开谷歌浏览器.py
@IDE :PyCharm
@Author :一晌小贪欢(278865463@qq.com)
@Date :2024/10/28 下午8:40
'''
import subprocess
from pathlib import Path
import psutil
def find_chrome():
common_paths = [
r"C:\Program Files\Google\Chrome\Application\chrome.exe",
r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"
]
for path in common_paths:
if Path(path).is_file():
return path
return None
def is_chrome_running_on_port(port):
result = subprocess.run(['netstat', '-ano'], capture_output=True, text=True)
lines = result.stdout.splitlines()
for line in lines:
if f':{port}' in line:
pid = line.split()[-1]
try:
process = psutil.Process(int(pid))
if 'chrome.exe' in process.name().lower():
return True
except psutil.NoSuchProcess:
continue
return False
def launch_chrome_with_params(chrome_path):
if chrome_path is None:
print("Chrome not found")
return
user_data_dir = r"D:\selenium"
remote_debugging_port = 9222
if is_chrome_running_on_port(remote_debugging_port):
print(f"Chrome is already running on port {remote_debugging_port}.")
return
chrome_command = f'"{chrome_path}" --remote-debugging-port={remote_debugging_port} --user-data-dir="{user_data_dir}"'
subprocess.Popen(chrome_command, shell=True)
if __name__ == "__main__":
chrome_path = find_chrome()
launch_chrome_with_params(chrome_path)
5、使用Selenium连接到远程调试端口
-
webdriver.Chrome() 配置为使用已开启调试端口的Chrome实例
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
chrome_options = Options()
chrome_options.add_experimental_option('debuggerAddress', '127.0.0.1:9222')
driver = webdriver.Chrome(options=chrome_options)
driver.get('http://www.baidu.com')
input_ = driver.find_element(By.ID,"kw")
input_.send_keys("python")
button = driver.find_element(By.ID,"su")
button.click()
总结
-
希望对初学者有帮助
-
致力于办公自动化的小小程序员一枚
-
希望能得到大家的【一个免费关注】!感谢
-
求个 🤞 关注 🤞
-
-
求个 ❤️ 喜欢 ❤️
-
-
求个 👍 收藏 👍
-