Selenium是一个Web的自动化测试工具,最初是为网站自动化测试而开发的,类型像我们玩游戏用的按键精灵,可以按指定的命令自动操作,不同是Selenium 可以直接运行在浏览器上,它支持所有主流的浏览器(包括PhantomJS这些无界面的浏览器)。
Selenium 可以根据我们的指令,让浏览器自动加载页面,获取需要的数据,甚至页面截屏,或者判断网站上某些动作是否发生。
Selenium 自己不带浏览器,不支持浏览器的功能,它需要与第三方浏览器结合在一起才能使用。但是我们有时候需要让它内嵌在代码中运行,所以我们可以用一个叫 PhantomJS 的工具代替真实的浏览器。
PhantomJS是一个而基于WebKit的服务端 API,支持Web而不需要浏览器支持,其快速、原生支持各种Web标准:Dom处理,CSS选择器,JSON等等。PhantomJS可以用用于页面自动化、网络监测、网页截屏,以及无界面测试。
声明浏览器对象
上面我们知道了selenium支持很多的浏览器,但是如果想要声明并调用浏览器则需要:
from selenium import webdriver
browser = webdriver.Chrome()
browser = webdriver.Firefox()
这里只写了两个例子,当然了其他的支持的浏览器都可以通过这种方式调用。在生声明浏览器的时候需要对webdriver进行配置。可百度。
访问页面
from selenium import webdriver
browser = webdriver.Chrome()
browser.get(\"http://www.baidu.com\")
print(browser.page_source)
browser.close()
上述代码运行后,会自动打开Chrome浏览器,并登陆百度打印百度首页的源代码,然后关闭浏览器
查找元素
单个元素查找
from selenium import webdriver
browser = webdriver.Chrome()
browser.get(\"http://www.taobao.com\")
input_first = browser.find_element_by_id(\"q\")
input_second = browser.find_element_by_css_selector(\"#q\")
input_third = browser.find_element_by_xpath(\'//*[@id=\"q\"]\')
print(input_first)
print(input_second)
print(input_third)
browser.close()
这里列举一下常用的查找元素方法:
find_element_by_name
find_element_by_id
find_element_by_xpath
find_element_by_ _text
find_element_by_partial_ _text
find_element_by_tag_name
find_element_by_class_name
find_element_by_css_selector
方法二:
from selenium.webdriver.common.by import By
from selenium import webdriver
from selenium.webdriver.common.by import By
browser = webdriver.Chrome()
browser.get(\"http://www.taobao.com\")
input_first = browser.find_element(By.ID,\"q\")
print(input_first)
browser.close()
当然browser.find_element(By.ID,“q”)这里By.ID中的ID可以替换为其他几个。
多个元素查找
其实多个元素和单个元素的区别,举个例子:find_elements,单个元素是find_element,其他使用上没什么区别,通过其中的一个例子演示:
from selenium import webdriver
browser = webdriver.Chrome()
browser.get(\"http://www.taobao.com\")
lis = browser.find_elements_by_css_selector(\'.service-bd li\')
print(lis)
browser.close()
元素交互操作
对于获取的元素调用交互方法
from selenium import webdriver
import time
browser = webdriver.Chrome()
browser.get(\"http://www.taobao.com\")
input_str = browser.find_element_by_id(\'q\')
input_str.send_keys(\"ipad\")
time.sleep(1)
input_str.clear()
input_str.send_keys(\"MakBook pro\")
button = browser.find_element_by_class_name(\'btn-search\')
button.click() #点击
运行的结果可以看出程序会自动打开Chrome浏览器并打开淘宝输入ipad,然后删除,重新输入MakBook pro,并点击搜索。
获取元素属性
get_attribute(‘class’)
from selenium import webdriver
browser = webdriver.Chrome()
url = \'https://www.zhihu.com/explore\'
browser.get(url)
logo = browser.find_element_by_id(\'zh-top- -logo\')
print(logo)
print(logo.get_attribute(\'class\'))
获取文本值
text
f
rom selenium import webdriver
browser = webdriver.Chrome()
url = \'https://www.zhihu.com/explore\'
browser.get(url)
input = browser.find_element_by_class_name(\'zu-top-add-question\')
print(input.text)
获取ID,位置,标签名
id
location
tag_name
size
from selenium import webdriver
browser = webdriver.Chrome()
url = \'https://www.zhihu.com/explore\'
browser.get(url)
input = browser.find_element_by_class_name(\'zu-top-add-question\')
print(input.id)
print(input.location)
print(input.tag_name)
print(input.size)
鼠标动作链
有些时候,我们需要再页面上模拟一些鼠标操作,比如双击、右击、拖拽甚至按住不动等,我们可以通过导入 ActionChains 类来做到:
#导入 ActionChains 类
from selenium.webdriver import ActionChains
# 鼠标移动到 ac 位置
ac = driver.find_element_by_xpath(\'element\')
ActionChains(driver).move_to_element(ac).perform()
# 在 ac 位置单击
ac = driver.find_element_by_xpath(\"elementA\")
ActionChains(driver).move_to_element(ac).click(ac).perform()
# 在 ac 位置双击
ac = driver.find_element_by_xpath(\"elementB\")
ActionChains(driver).move_to_element(ac).double_click(ac).perform()
# 在 ac 位置右击
ac = driver.find_element_by_xpath(\"elementC\")
ActionChains(driver).move_to_element(ac).context_click(ac).perform()
# 在 ac 位置左键单击hold住
ac = driver.find_element_by_xpath(\'elementF\')
ActionChains(driver).move_to_element(ac).click_and_hold(ac).perform()
# 将 ac1 拖拽到 ac2 位置
ac1 = driver.find_element_by_xpath(\'elementD\')
ac2 = driver.find_element_by_xpath(\'elementE\')
ActionChains(driver).drag_and_drop(ac1, ac2).perform()
**填充表单**
Selenium专门提供了Select类来处理下拉框。 其实 WebDriver 中提供了一个叫 Select 的方法,可以帮助我们完成这些事情:
# 导入 Select 类
from selenium.webdriver.support.ui import Select
# 找到 name 的选项卡
select = Select(driver.find_element_by_name(\'status\'))
#
select.select_by_index(1)
select.select_by_value(\"0\")
select.select_by_visible_text(u\"未审核\")
以上是三种选择下拉框的方式,它可以根据索引来选择,可以根据值来选择,可以根据文字来选择。注意:
- index 索引从 0 开始
- value是option标签的一个属性值,并不是显示在下拉框中的值
- visible_text是在option标签文本的值,是显示在下拉框的值 visible_text是在option标签文本的值,是显示在下拉框的值
弹窗处理
当你触发了某个事件之后,页面出现了弹窗提示,处理这个提示或者获取提示信息方法如下:
alert = driver.switch_to_alert()
页面切换
一个浏览器肯定会有很多窗口,所以我们肯定要有方法来实现窗口的切换。切换窗口的方法如下:
driver.switch_to.window(\"this is window name\")
也可以使用 window_handles 方法来获取每个窗口的操作对象。例如:
for handle in driver.window_handles:
driver.switch_to_window(handle)
页面前进和后退
操作页面的前进和后退功能:
driver.forward() #前进
driver.back() # 后退
Cookies
获取页面每个Cookies值,用法如下
f
or cookie in driver.get_cookies():
print \"%s -> %s\" % (cookie[\'name\'], cookie[\'value\'])
删除Cookies,用法如下
# By name
driver.delete_cookie(\"CookieName\")
# all
driver.delete_all_cookies()
页面等待
当使用了隐式等待执行测试的时候,如果 WebDriver没有在 DOM中找到元素,将继续等待,超出设定时间后则抛出找不到元素的异常, 换句话说,当查找元素或元素并没有立即出现的时候,隐式等待将等待一段时间再查找 DOM,默认的时间是0
隐式等待
到了一定的时间发现元素还没有加载,则继续等待我们指定的时间,如果超过了我们指定的时间还没有加载就会抛出异常,如果没有需要等待的时候就已经加载完毕就会立即执行
from selenium import webdriver
browser = webdriver.Chrome()
browser.implicitly_wait(10)
browser.get(\'https://www.zhihu.com/explore\')
input = browser.find_element_by_class_name(\'zu-top-add-question\')
print(input)
显示等待
指定一个等待条件,并且指定一个最长等待时间,会在这个时间内进行判断是否满足等待条件,如果成立就会立即返回,如果不成立,就会一直等待,直到等待你指定的最长等待时间,如果还是不满足,就会抛出异常,如果满足了就会正常返回
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
browser = webdriver.Chrome()
browser.get(\'https://www.taobao.com/\')
wait = WebDriverWait(browser, 10)
input = wait.until(EC.presence_of_element_located((By.ID, \'q\')))
button = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, \'.btn-search\')))
print(input, button)
上述的例子中的条件:EC.presence_of_element_located()是确认元素是否已经出现了
EC.element_to_be_clickable()是确认元素是否是可点击的
常用的判断条件:
_is 标题是某内容
_contains 标题包含某内容
presence_of_element_located 元素加载出,传入定位元组,如(By.ID, ‘p’)
visibility_of_element_located 元素可见,传入定位元组
visibility_of 可见,传入元素对象
presence_of_all_elements_located 所有元素加载出
text_to_be_present_in_element 某个元素文本包含某文字
text_to_be_present_in_element_value 某个元素值包含某文字
_to_be_available_and_switch_to_it 加载并切换
invisibility_of_element_located 元素不可见
element_to_be_clickable 元素可点击
staleness_of 判断一个元素是否仍在DOM,可判断页面是否已经刷新
element_to_be_selected 元素可选择,传元素对象
element_located_to_be_selected 元素可选择,传入定位元组
element_selection_state_to_be 传入元素对象以及状态,相等返回True,否则返回False
element_located_selection_state_to_be 传入定位元组以及状态,相等返回True,否则返回False
alert_is_present 是否出现Alert
异常处理
from selenium import webdriver
from selenium.common.exceptions import TimeoutException, NoSuchElementException
browser = webdriver.Chrome()
try:
browser.get(\'https://www.baidu.com\')
except TimeoutException:
print(\'Time Out\')
try:
browser.find_element_by_id(\'hello\')
except NoSuchElementException:
print(\'No Element\')
finally:
browser.close()
案例一:网站模拟登录
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
class Douban():
def __init__(self):
self.url = \"https://www.douban.com/\"
self.driver = webdriver.PhantomJS()
def log_in(self):
self.driver.get(self.url)
time.sleep(3)#睡3分钟,等待页面加载
self.driver.save_screenshot(\"0.jpg\")
#输入账号
self.driver.find_element_by_xpath(\'//*[@id=\"form_email\"]\').send_keys(\"xxxxx@qq.com\")
#输入密码
self.driver.find_element_by_xpath(\'//*[@id=\"form_password\"]\').send_keys(\"xxxx\")
#点击登陆
self.driver.find_element_by_class_name(\"bn-submit\").click()
time.sleep(2)
self.driver.save_screenshot(\"douban.jpg\")
#输出登陆之后的cookies
print(self.driver.get_cookies())
def __del__(self):
\'\'\'调用内建的稀构方法,在程序退出的时候自动调用
类似的还可以在文件打开的时候调用close,数据库链接的断开
\'\'\'
self.driver.quit()
if __name__ == \"__main__\":
douban = Douban() #实例化
douban.log_in() #之后调用登陆方法
案例二:动态页面模拟点击
爬取斗鱼直播平台的所有房间信息:
from selenium import webdriver
import json
import time
class Douyu:
# 1.发送首页的请求
def __init__(self):
self.driver = webdriver.PhantomJS()
self.driver.get(\"https://www.douyu.com/directory/all\") #请求首页
#获取没页面内容
def get_content(self):
time.sleep(3) #每次发送完请求等待三秒,等待页面加载完成
li_list = self.driver.find_elements_by_xpath(\'//ul[@id=\"live-list-contentbox\"]/li\')
contents = []
for i in li_list: #遍历房间列表
item = {}
item[\"img\"] = i.find_element_by_xpath(\"./a//img\").get_attribute(\"src\") #获取房间图片
item[\" \"] = i.find_element_by_xpath(\"./a\").get_attribute(\" \") #获取房间名字
item[\"category\"] = i.find_element_by_xpath(\"./a/div[@class=\'mes\']/div/span\").text #获取房间分类
item[\"name\"] = i.find_element_by_xpath(\"./a/div[@class=\'mes\']/p/span[1]\").text #获取主播名字
item[\"watch_num\"] = i.find_element_by_xpath(\"./a/div[@class=\'mes\']/p/span[2]\").text #获取观看人数
print(item)
contents.append(item)
return contents
#保存本地
def save_content(self,contents):
f = open(\"douyu.txt\",\"a\")
for content in contents:
json.dump(content,f,ensure_ascii=False,indent=2)
f.write(\"\\n\")
f.close()
def run(self):
#1.发送首页的请求
#2.获取第一页的信息
contents = self.get_content()
#保存内容
self.save_content(contents)
#3.循环 点击下一页按钮,知道下一页对应的class名字不再是\"shark-pager-next\"
while self.driver.find_element_by_class_name(\"shark-pager-next\"): #判断有没有下一页
#点击下一页的按钮
self.driver.find_element_by_class_name(\"shark-pager-next\").click() #
# 4.继续获取下一页的内容
contents = self.get_content()
#4.1.保存内容
self.save_content(contents)
if __name__ == \"__main__\":
douyu = Douyu()
douyu.run()
加油!!!
继续阅读与本文标签相同的文章
Golang 垃圾回收剖析
-
十位大师零距离,云栖大会通票+限量周边,还不够诱人吗亲? | 开发者必读(062期)
2026-05-18栏目: 教程
-
相同类中方法间调用时日志Aop失效处理
2026-05-18栏目: 教程
-
“2019密码应用高峰论坛”,探讨国密证书全生态应用
2026-05-18栏目: 教程
-
阿里云ECS突发性能t6实例1年仅需148元 上车拼团即享1.5折优惠!
2026-05-18栏目: 教程
-
Linux初级知识
2026-05-18栏目: 教程
