python Selenium

Selenium概述

Selenium是一个用于web应用程序测试的工具,模拟浏览器功能,自动执行网页中的is代码,实现动态加载

支持通过各种driver (FirfoxDriver,IternetExplorerDriver,OperaDriver,chromeDriver) 驱动直实浏览器完成测试,Selenium也是支持无界面浏览器操作的

Selenium安装

下载chrome驱动

根据chrome浏览器版本下载驱动

https://registry.npmmirror.com/binary.html?path=chromedriver/

移动至项目文件根目录

安装 selenium

python 复制代码
# 这里我选的是3.5.0版本 最好不要选择最新版本
pip install selenium -i  https://pypi.tuna.tsinghua.edu.cn/simple

Selenium的使用

python 复制代码
from selenium import webdriver

# 创建浏览器操作对象
browser = webdriver.Chrome("chromedriver.exe")

# 访问百度网站
url = 'https://www.baidu.com'

browser.get(url)

# 获取网页源码
content = browser.page_source

print(content)

Selenium元素定位

selenium的元素定位:webDriver提供很多定位元素的方法:

老版本写法

  • find_element by_id
  • find_elements_by_name
  • find**_elements_by_xpath**
  • find**** elements by_tag**** name
  • find**** elements**** by**** css**** selector
  • find**** elements**** by**** link**** text

新版本写法

  • find_element
  • find_elments
python 复制代码
# 根据xpath选择元素(最常用)
driver.find_element(By.XPATH, '//*[@id="kw"]') 
# 根据css选择器选择元素
driver.find_element(By.CSS_SELECTOR, '#kw') 
# 根据name属性值选择元素
driver.find_element(By.NAME, 'wd') 
# 根据类名选择元素
driver.find_element(By.CLASS_NAME, 's_ipt') 
# 根据链接文本选择元素
driver.find_element(By.LINK_TEXT, 'hao123') 
# 根据包含文本选择
driver.find_element(By.PARTIAL_LINK_TEXT, 'hao') 
# 根据标签名选择
# 目标元素在当前html中是唯一标签或众多标签第一个时候使用
driver.find_element(By.TAG_NAME, 'title') 
# 根据id选择
driver.find_element(By.ID, 'su') 

无界面浏览器使用

Phantomjs

Phantomjs是一个无界面的浏览器,支持页面元素查找,js的执行等,由于不进行css和gui渲染,运行效率要比真实的浏览器要快很多,可以保存快照查看

除phantomjs之外,还可以使用Chrome handless,不过 Chrome handless 有版本要求,这里不在演示

下载Phantomjs

下载地址: Download PhantomJS

使用无界面浏览器

python 复制代码
from selenium import webdriver
import time

# 创建浏览器操作对象
browser = webdriver.PhantomJS("phantomjs.exe")

# 访问百度网站
url = 'https://www.baidu.com'

browser.get(url)

# 保存快照
browser.save_screenshot('baidu.png')

time.sleep(2)

input = browser.find_element_by_id('kw')

input.send_keys("陈奕迅")

# 保存快照
browser.save_screenshot('陈奕迅.png')

验证快照

相关推荐
沈浩(种子思维作者)43 分钟前
系统要活起来就必须开放包容去中心化
人工智能·python·flask·量子计算
2301_790300961 小时前
Python数据库操作:SQLAlchemy ORM指南
jvm·数据库·python
weixin_499771551 小时前
C++中的组合模式
开发语言·c++·算法
初级代码游戏1 小时前
套路化编程 C# winform 自适应缩放布局
开发语言·c#·winform·自动布局·自动缩放
_waylau1 小时前
鸿蒙架构师修炼之道-架构师的职责是什么?
开发语言·华为·harmonyos·鸿蒙
2的n次方_1 小时前
CANN Ascend C 编程语言深度解析:异构并行架构、显式存储层级与指令级精细化控制机制
c语言·开发语言·架构
m0_736919101 小时前
用Pandas处理时间序列数据(Time Series)
jvm·数据库·python
getapi1 小时前
实时音视频传输与屏幕共享(投屏)
python
java干货2 小时前
为什么 “File 10“ 排在 “File 2“ 前面?解决文件名排序的终极算法:自然排序
开发语言·python·算法
_F_y2 小时前
C语言重点知识总结(含KMP详细讲解)
c语言·开发语言