# selenium_demo **Repository Path**: alienshen133/selenium_demo ## Basic Information - **Project Name**: selenium_demo - **Description**: 软件测试Selenium章节上课相关示例代码 - **Primary Language**: Python - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 1 - **Forks**: 0 - **Created**: 2024-12-01 - **Last Updated**: 2025-06-30 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README

Selenium环境安装配置

1. 引入selenium库和下载chrome web driver

pip install selenium

from selenium import webdriver
from selenium.webdriver.chrome.service import Service

Chrom Web Driver Download

3. 让浏览器打开指定网页

wd.get("https://www.taobao.com")

4. 更多webdiver的操作可以参考

参考

元素的选择

引用By库 from selenium.webdriver.common.by import By

1. 根据id选择

在浏览器开发者工具里面找元素id
根据id选择页面元素,返回WebElement对象
element=wd.find_element(By.ID,"suggestion-search")
通过此WebElement对象,对页面元素进行操作,
比如输入字符串
element.send_keys("ironman 3")
比如按下回车
element.send_keys("\n")\

2. 根据class选择

跟用id查找类似,在浏览器开发者工具里面找元素class
根据class选择页面元素,返回WebElement对象列表
elements=wd.find_elements(By.CLASS_NAME,"ipc-image") 可以循环elements列表中的内容

3. 根据标签选择

elements=wd.find_elements(By.TAG_NAME,"meta")

4. webdriver.find_element() vs element.find_element()

webdriver是搜索整个页面,element是搜索页面内部

5.implicity_wait

当找不到元素的时候,并不立即返回错误,而是等待一段时间
wd.implicity_wait(10)
加入这行代码以后,find_element之类的查询元素的方法会每隔半秒钟去界面上查看一次直到找到元素,或者超过10秒最大时常

6.操作元素本身

7.切换到新窗口

如果需要切换到新窗口操作使用Webdriver对象的switch_to属性的window方法 wd.switch_to.window(handle)
其中handle是窗口的句柄,或者可以认为是窗口的id

8.ActionChains

有时候需要进行一连串的操作,需要用到actionchain
引用from selenium.webdriver.common.action_chains import ActionChains ac=ActionChains(wd)
具体操作可以参考1. 中得了链接,比如 ac.move_to_element(search).move_by_offset(-10,0).click().send_keys("作息表\n").perform()