selenium
这篇文章最后更新于 some 天前,内容可能已经过时。
一、环境搭建 1. 安装三方库 1 2 3 pip install selenium pip install password pip install time
2. 安装浏览器驱动
简单起见将下载的driver.exe与py文件放在同一目录下,可以不用配置环境变量。
二、初始化 1. 导入模块 1 2 3 4 5 6 7 import timefrom selenium import webdriverfrom selenium.webdriver.chrome.options import Optionsfrom selenium.webdriver.chrome.service import Servicefrom selenium.webdriver.common.by import Byimport password
2. 设置浏览器配置 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 def Auto (): rio = Options() rio.add_argument('--no-sandbox' ) rio.add_argument('--start-maximized' ) rio.add_experimental_option('detach' , True ) RIO = webdriver.Chrome(service=Service(r'.\chromedriver.exe' ), options=rio) return RIO RIO=Auto()
3. 打开网站 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 RIO.get('URL' ) time.sleep(1 ) RIO.find_element(By.CSS_SELECTOR, '' ).click() RIO.find_element(By.ID, '' ).send_keys(password.username) RIO.find_element(By.ID, '' ).send_keys(password.password) RIO.find_element(By.CSS_SELECTOR, '' ).click() current_time = datetime.now().strftime('%Y-%m-%d_%H-%M-%S' ) RIO.save_screenshot(f'screenshot_{current_time} .png' ) time.sleep(8 )
4. 程序的最后关闭浏览器驱动
三、选择元素 1. 根据ID查找 1 element = wd.find_element(By.ID, 'ID值' )
2. 根据CSS选择器查找 1 element = wd.find_element(By.CSS_SELECTOR, 'css选择器' )
3. 其他查找方法 1 2 element = wd.find_element(By.CLASS_NAME, 'class属性' ) element = wd.find_element(By.TAG_NAME, '标签名' )
4. FIND_ELEMENT与FIND_ELEMENTS 1 2 find_element返回一个元素(第一个) find_elements返回元素列表
四、操作元素 1. 输入文字:SEND_KEYS()
2. 点击:CLICK()
3. 下拉框选择 1 2 3 s = Select(element) s.select_by_value('value值' )
五、切换窗口 1. IFRAME 1 2 3 4 5 6 wd.switch_to.frame('iframe名' ) wd.switch_to.default_content()
2. 切换页面 1 2 3 4 for window_handle in wd.window_handles: wd.switch_to.window(window_handle) if '内容' in wd.title: break
六、打包程序
1 Pyinstaller -F -w -i *.ico *.py
标题: selenium
作者: Jiu_Ying
创建于
: 2025-08-27 03:15:38
更新于
: 2025-08-27 03:15:38
链接: http://rio.jiu-ying.top/2025/08/27/selenium/
版权声明:
本文章采用 CC BY-NC-SA 4.0 进行许可。