python中selenium爬虫环境准备
下载谷歌测试组件
谷歌官网下载stable标准版的chromedriver驱动和Google Chrome for Testing浏览器
安装selenium
安装最新版本
验证版本
卸载
指定版本安装
验证版本
pip3 install seleniumpip show seleniumpip uninstall seleniumpip install selenium==4.1.1pip show selenium
说明:需要挂代理或者国内镜像
版本
目前使用的版本为:
| 名称 | 版本 |
|---|---|
| Python | 3.12.2 |
| selenium | 4.1.1 |
| chromedriver.exe | 134.0.6998.88 |
| Google Chrome for Testing | 134.0.6998.88 |
环境配置
import timeimport tracebackimport sysimport osfrom datetime import datetimefrom selenium import webdriverfrom selenium.webdriver.common.by import Byfrom selenium.common.exceptions import NoSuchElementExceptionglobal driveroptions = webdriver.ChromeOptions()# options.add_argument('--ignore-certificate-errors') # http模式不可使用options.add_experimental_option('excludeSwitches', ['enable-automation', 'enable-logging'])options.binary_location = r'.\tools\chrome-win64\chrome.exe'driver = webdriver.Chrome(options=options, executable_path=r'.\tools\chromedriver.exe')
指定谷歌套件路径
- 指定chrome.exe
options.binary_location = r'.\tools\chrome-win64\chrome.exe'
- 指定chromedriver.exe
driver = webdriver.Chrome(options=options, executable_path=r'.\tools\chromedriver.exe')
查找元素
- id
driver.find_element(By.ID, 'ctl00_ContentPlaceHolder1_Signin1_txtEmail').send_keys(user)
class
driver.find_elements(By.CLASS_NAME, 'el-input__inner')[0].send_keys(user)
说明:有多个时是elements。
带空格的class
改成CSS_SELECTOR元素就可以定位到了。el-select-dropdown__item selected hover # class名称.el-select-dropdown__item.hover # 转换为css元素
最后写出来是这样
driver.find_element(By.CSS_SELECTOR, '.el-select-dropdown__item.hover').click()
SS_SELECTOR是需要延迟执行的,大概2秒。
xpath
driver.find_element(By.XPATH, '//*[@id="app"]/div[2]/div[2]/div/div/div/div/button').click()
元素动作
鼠标点击
driver.find_element(By.XPATH, '//*[@id="app"]/div[2]/div[2]/div/div/div/div/button').click()
鼠标悬停
from selenium.webdriver.common.action_chains import ActionChains
获取元素信息
检测复选框是否为选中状态
driver.find_element(By.CLASS_NAME, 'el-checkbox__inner').is_selected()
获取元素文本内容
driver.find_element(By.XPATH, '//*[@id="dropdown-menu-4658"]/li[2]').text
切换到最新页面
window_handles = driver.window_handlesnew_window = window_handles[-1]driver.switch_to.window(new_window)
创建新标签页
driver.execute_script("window.open('');")# 创建后需要切换到最新页面window_handles = driver.window_handlesnew_window = window_handles[-1]driver.switch_to.window(new_window)# 退出页面需要回到之前第一个页面driver.close()all_handles = driver.window_handlesdriver.switch_to.window(all_handles[0])
获取页面标题
可以获取页面标题来确认当前页面
print(driver.title)
iframe
iframe是 HTML 中的一个标签,即内联框架(Inline Frame),用于在当前 HTML 文档中嵌入另一个文档或网页。
有些元素在iframe中无法被定位到,需要切换进去。
iframe = driver.find_element(By.ID, 'iframe')driver.switch_to.frame(iframe)
切换回默认iframe
driver.switch_to.default_content()
获取视频的时长
def playVideo():iframeVideo = driver.find_element(By.CSS_SELECTOR, 'iframe.ans-attach-online.ans-insertvideo-online')driver.switch_to.frame(iframeVideo)video = driver.find_element(By.TAG_NAME, 'video')driver.execute_script("arguments[0].play();", video)total_duration = driver.execute_script("return arguments[0].duration;", video)current_time = driver.execute_script("return arguments[0].currentTime;", video)remaining_time = total_duration - current_timeprint(remaining_time) # 剩余播放时长
检测视频是否停止播放
driver.execute_script("return arguments[0].paused || arguments[0].ended;", video)
返回True则是停止或者暂停播放,返回False则是正在播放
用while循环一直检测
is_stopped = Falsewhile not is_stopped:is_stopped = driver.execute_script("return arguments[0].paused || arguments[0].ended;", video)time.sleep(1)
注意:while最后不能加break,否则只运行一次就跳出循环了。
获取aria-label属性
driver.find_element(By.ID, 'ext-gen1051').get_attribute('aria-label')
aria-label 属性:主要是为辅助设备提供文本信息,通常在页面上不显示
此处会遇到错误等待一秒后自动循环,成功后退出循环。
元素数量查询
iframes = driver.find_elements(By.ID, 'iframe')print(len(iframes))