python Selenium 库的使用技巧
作者:lyshark 时间:2021-08-07 21:23:47
Selenium 是一个用于Web应用程序测试的工具。Selenium测试直接运行在浏览器中,就像真正的用户在操作一样。支持的浏览器包括IE,Mozilla Firefox,Safari,Google Chrome,Opera等。这个工具的主要功能包括:测试与浏览器的兼容性——测试你的应用程序看是否能够很好得工作在不同浏览器和操作系统之上。测试系统功能——创建回归测试检验软件功能和用户需求。支持自动录制动作和自动生成 .Net、Java、Perl等不同语言的测试脚本。 -- 百度百科
首先下载驱动文件:https://chromedriver.storage.googleapis.com/index.html?path=2.39/
放入google目录下
测试代码,测试是否能读取到驱动文件。
from selenium import webdriver
path = "C:/Users/LyShark/AppData/Local/Google/Chrome/Application/chromedriver.exe"
driver = webdriver.Chrome(executable_path=path)
url = "https://www.baidu.com"
driver.get(url)
print(driver.page_source)
简单的实现浏览器测试
# -*- coding:utf-8 -*-
from selenium import webdriver
WebPath = "C:/Users/LyShark/AppData/Local/Google/Chrome/Application/chromedriver.exe"
driver = webdriver.Chrome(executable_path=WebPath)
driver.set_window_size(1000,500)
url = "https://www.baidu.com"
driver.get(url)
print(driver.find_element_by_id("kw"))
Selenium 自动化测试库的使用:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="gbk">
<title>Selenium Test</title>
</head>
<body>
<div class="acount" id="aid">
<a class="mnav" href="https://news.baidu.com" rel="external nofollow" name="trnews">新闻</a>
<a class="mnav" href="https://lyshark.cnblogs.com" rel="external nofollow" name="myblog">我的博客</a>
<a class="mnav" href="https://github.com/lyshark" rel="external nofollow" name="mygit">GitHub</a>
</div>
<form id="forms" class="fms" name="submit_form" action="index.html">
<span class="soutu-btn"></span>
<p>用户: <input id="user" class="s_ipt" name="wd" value="" maxlength="255" autocomplete="off"></p>
<p>密码: <input id="pass" class="s_ipt" name="wd" value="" maxlength="255" autocomplete="off"></p>
<input type="submit" value="提交" />
</form>
<p name="p1" > hello lyshark p1</p>
<p name="p2" > hello lyshark p2</p>
</body>
</html>
通过简单的浏览文件并实现简单的定位.
# 驱动下载地址: http://chromedriver.storage.googleapis.com/index.html
from selenium import webdriver
WebPath = "C:/Users/LyShark/AppData/Local/Google/Chrome/Application/chromedriver.exe"
driver = webdriver.Chrome(executable_path=WebPath)
driver.set_window_size(1024,768)
# 常用的定位变量参数如下所示.
driver.get("http://lyshark.com")
print("当前URL: {}".format(driver.current_url))
print("当前标题: {}".format(driver.title))
print("网页代码: {}".format(driver.page_source))
# 基本的 find_element 标签查找定位方式
print(driver.find_element_by_id("user")) # 通过ID来查找元素
print(driver.find_element_by_name("p1").text) # 通过name属性来定位
print(driver.find_element_by_class_name("s_ipt")) # 通过类名来定位
# 通过xpath定位,xpath定位有N种写法,这里列几个常用写法
print(driver.find_element_by_xpath("//form[@class='fms']//input[@id='user']"))
print(driver.find_element_by_xpath("//p[@name='p1']"))
print(driver.find_element_by_xpath("//html/body/form/p/input"))
print(driver.find_elements_by_css_selector(".fms #user"))
# 定位a标签中的关键字.
print(driver.find_element_by_link_text("新闻"))
print(driver.find_element_by_partial_link_text("我"))
通过xpath定位标签并自动输入内容,发送登录请求到后端,写法如下.
from selenium import webdriver
WebPath = "C:/Users/LyShark/AppData/Local/Google/Chrome/Application/chromedriver.exe"
driver = webdriver.Chrome(executable_path=WebPath)
driver.set_window_size(1024,768)
driver.get("http://lyshark.com")
# 通过xpath语法定位到用户名的标签上并且自动输入lyshark这个用户名
driver.find_element_by_xpath("//form[@class='fms']/p//input[@id='user']").send_keys("lyshark")
# 通过xpath语法定位到密码的标签上清空默认值,然后输入123123密码
driver.find_element_by_xpath("//form[@class='fms']/p//input[@id='pass']").clear()
driver.find_element_by_xpath("//form[@class='fms']/p//input[@id='pass']").send_keys("123123")
# 提交这个请求,默认有两种提交方式一种是 click() 一种是submit()
driver.find_element_by_xpath("//form[@class='fms']/input[@type='submit']").click()
通过键盘鼠标类库记录并可回放
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.keys import Keys
WebPath = "C:/Users/LyShark/AppData/Local/Google/Chrome/Application/chromedriver.exe"
driver = webdriver.Chrome(executable_path=WebPath)
driver.set_window_size(1024,768)
driver.get("https://www.baidu.com")
# ------------------------------------------------------------------------
# ActionChains 类提供了鼠标操作的常用方法,鼠标事件的常用函数说明
# perform(): 鼠标悬浮于标签
# context_click(): 右击
# double_click(): 双击
# drag_and_drop(): 拖动
# move_to_element():鼠标悬停
# 定位到要悬停的元素
above = driver.find_element_by_link_text("更多产品")
# 对定位到的元素执行鼠标悬停操作
ActionChains(driver).move_to_element(above).perform()
# ------------------------------------------------------------------------
# webdriver.common.keys 类提供了键盘事件的操作,以下为常用的键盘操作:
# send_keys(Keys.BACK_SPACE) 删除键(BackSpace)
# send_keys(Keys.SPACE) 空格键(Space)
# send_keys(Keys.TAB) 制表键(Tab)
# send_keys(Keys.ESCAPE) 回退键(Esc)
# send_keys(Keys.ENTER) 回车键(Enter)
# send_keys(Keys.CONTROL,'a') 全选(Ctrl+A)
# send_keys(Keys.CONTROL,'c') 复制(Ctrl+C)
# send_keys(Keys.CONTROL,'x') 剪切(Ctrl+X)
# send_keys(Keys.CONTROL,'v') 粘贴(Ctrl+V)
# send_keys(Keys.F1) 键盘 F1
# 输入框输入内容
driver.find_element_by_id("kw").send_keys("seleniumm")
# 删除多输入的一个 m
driver.find_element_by_id("kw").send_keys(Keys.BACK_SPACE)
# 输入空格键+从入门到入土
driver.find_element_by_id("kw").send_keys(Keys.SPACE)
driver.find_element_by_id("kw").send_keys("从入门到入土")
# ctrl+a 全选输入框内容
driver.find_element_by_id("kw").send_keys(Keys.CONTROL, 'a')
# ctrl+x 剪切输入框内容
driver.find_element_by_id("kw").send_keys(Keys.CONTROL, 'x')
# ctrl+v 粘贴内容到输入框
driver.find_element_by_id("kw").send_keys(Keys.CONTROL, 'v')
# 通过回车键来代替单击操作
driver.find_element_by_id("su").send_keys(Keys.ENTER)
简单的点击事件
# -*- coding:utf-8 -*-
from selenium import webdriver
import time
WebPath = "C:/Users/LyShark/AppData/Local/Google/Chrome/Application/chromedriver.exe"
driver = webdriver.Chrome(executable_path=WebPath)
driver.set_window_size(1024,768)
driver.get("https://www.baidu.com")
driver.find_element_by_id("kw").send_keys("lyshark") # 发送给id=kw的编辑框,搜索关键字 lyshark
driver.find_element_by_id("su").click() # 点击搜索按钮,百度一下的ID是su
time.sleep(1)
# xpath 语法 寻找 div id是1里面的 a标签取出标签中的 contains text()
driver.find_element_by_xpath("//div[@id='1']//a[contains(text(),'-')]").click()
time.sleep(1)
handle = driver.current_window_handle # 获取当前窗口句柄
handle_all = driver.window_handles # 获取当前所有开启窗口的句柄
print(handle_all)
driver.switch_to.window(handle_all[0]) # 切换到第一个窗口中
time.sleep(1)
driver.find_element_by_id("kw").clear() # 接着清空搜索框中的内容
百度自动收集
from selenium import webdriver
from bs4 import BeautifulSoup
from queue import Queue
import requests,os,re,lxml
# driver: http://chromedriver.storage.googleapis.com/index.html?path=79.0.3945.36/
head = {"User-Agent":"Mozilla/5.0 (iPhone; U; CPU like Mac OS X) AppleWebKit/420.1 (KHTML, like Gecko) Version/3.0 Mobile/4A93 Safari/419.3"}
WebPath = "C:/Users/LyShark/AppData/Local/Google/Chrome/Application/chromedriver.exe"
driver = webdriver.Chrome(executable_path=WebPath)
queue = Queue()
for item in range(0,1000,10):
queue.put('https://www.baidu.com/s?wd={}&pn={}'.format("lyshark",str(item)))
for item in queue.queue:
driver.get(item)
ret = str(driver.page_source)
try:
soup = BeautifulSoup(ret,'lxml')
urls = soup.find_all(name='a',attrs={'data-click':re.compile(('.')),'class':None})
for item in urls:
get_url = requests.get(url=item['href'],headers=head,timeout=5)
if get_url.status_code == 200:
print(get_url.url)
except Exception:
pass
页面等待
from selenium import webdriver
driver=webdriver.Chrome()
driver.get('https://www.taobao.com/')
wait=WebDriverWait(driver,3) #设置监听driver等待时间3秒
input=wait.until(EC.presence_of_element_located((By.ID,'q'))) #设置等待条件为id为q的元素加载完成
button=wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,'.btn-search'))) #设置等待条件为class名为btn-search的元素加载完成
print(input,button)
driver = webdriver.Firefox()
driver.implicitly_wait(10) #隐式等待设置为10等待时间
driver.get("http://somedomain/url_that_delays_loading")
myDynamicElement = driver.find_element_by_id("myDynamicElement")
键盘操作
element=driver.find_element_by_id('search') #获取输入框
element.send_keys('selenium') #搜索selenium包
element.send_keys(Keys.ENTER) #按回车键
element_a=driver.find_element_by_link_text('selenium') #定位selenium包链接
ActionChains(driver).move_to_element(element_a).click(element_a).perform() #按左键点击链接执行
element_down=driver.find_element_by_link_text('Download files') #定位下载链接
ActionChains(driver).move_to_element(element_down).click(element_down).perform() #按左键点击链接
element_selenium=driver.find_element_by_link_text('selenium-3.13.0.tar.gz') #定位元素selenium下载包链接
data=element_selenium.get_attribute('href') #获取链接地址
with open('selenium-3.13.0.tar.gz','wb') as f:
source=requests.get(data).content #请求下载链接地址获取二进制包数据
f.write(source) #写入数据
f.close()
driver.quit()
menu = driver.find_element_by_css_selector(".nav") #获取element对象
hidden_submenu = driver.find_element_by_css_selector(".nav #submenu1") #获取点击对象
#创建鼠标对象
actions = ActionChains(driver)
#移动鼠标到对象
actions.move_to_element(menu)
#点击对象
actions.click(hidden_submenu)
#执行操作
actions.perform()
文章作者:lyshark
文章出处:https://www.cnblogs.com/lyshark
来源:https://www.cnblogs.com/LyShark/p/12173220.html
标签:python,Selenium,库
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python 通过exifread读取照片信息
2022-12-09 13:44:53
一个可应用在ASP 标记加密文件的MD5的DLL组件
2008-04-12 07:21:00
微信小程序跳一跳游戏 python脚本跳一跳刷高分技巧
2023-01-31 22:30:44
![](https://img.aspxhome.com/file/2023/7/66807_0s.png)
css+JavaScript实现PDF、ZIP、DOC链接的标注
2007-05-11 17:03:00
Python语法学习之进程池与进程锁详解
2021-09-01 23:16:17
![](https://img.aspxhome.com/file/2023/3/101333_0s.png)
SQL Server 2005数据库镜像配置脚本示例
2008-04-12 14:49:00
触手生春【4.14】CSS与HTML结构
2008-12-09 18:10:00
![](https://img.aspxhome.com/file/UploadPic/200812/9/22008111871736-53s.jpg)
浅谈SQL Server中统计对于查询的影响分析
2012-06-06 20:08:23
为你总结一些php信息函数
2023-10-28 09:46:59
python DataFrame中loc与iloc取数据的基本方法实例
2022-06-23 15:58:25
![](https://img.aspxhome.com/file/2023/8/67868_0s.png)
DW MX新功能试用:嵌套模板
2008-02-03 11:35:00
![](https://img.aspxhome.com/file/UploadPic/20072/200723113533349s.jpg)
利用python实现PSO算法优化二元函数
2022-06-17 20:53:04
![](https://img.aspxhome.com/file/2023/5/70225_0s.jpg)
Go语言interface详解
2023-07-05 16:55:33
JS复制特定内容到粘贴板
2011-04-02 11:09:00
Oracle中pivot函数图文实例详解
2023-07-12 22:13:49
![](https://img.aspxhome.com/file/2023/0/64450_0s.png)
php下intval()和(int)转换使用与区别
2023-06-11 14:09:54
SQL Server 2005 五个动态管理对象
2008-12-18 14:50:00
python图形界面tkinter的使用技巧
2022-04-24 01:34:22
![](https://img.aspxhome.com/file/2023/5/85195_0s.png)
Pycharm中的下载安装、配置与测试方式
2023-11-18 01:53:27
![](https://img.aspxhome.com/file/2023/2/101212_0s.png)
Python正确调用 jar 包加密得到加密值的操作方法
2021-02-26 12:12:19
![](https://img.aspxhome.com/file/2023/3/100913_0s.png)