selenium使用记录

本文记录python环境下使用selenium的一些步骤

Step1:安装并配置驱动

复制代码
pip install selenium # 使用pip在对应python中安装selenium包

为了让selenium能调用指定的浏览器,需要下载对应浏览器的驱动程序(这里以edge为例子)

复制代码
#Firefox浏览器驱动:
https://link.zhihu.com/?target=https%3A//github.com/mozilla/geckodriver/releases

#Chrome浏览器驱动:
https://registry.npmmirror.com/binary.html?path=chromedriver/

#IE浏览器驱动:IEDriverServer
https://link.zhihu.com/?target=http%3A//selenium-release.storage.googleapis.com/index.html

#Edge浏览器驱动:MicrosoftWebDriver
https://link.zhihu.com/?target=https%3A//developer.microsoft.com/en-us/microsoft-edge/tools/webdriver

在下载edge驱动时,请先在edge浏览器中输入:edge://settings/help用于查看版本和位数,选择相匹配的驱动版本,具体可以参考官方的教程:https://learn.microsoft.com/zh-cn/microsoft-edge/webdriver-chromium/?tabs=c-sharp

下载驱动后,需要放在项目的主目录下,或添加到全局变量中,如图所示:

Step2:打开网页返回代码

复制代码
from selenium import webdriver

options = webdriver.EdgeOptions()
options.add_experimental_option("detach", True)  # 该选项可避免打开的网页闪退
browser = webdriver.Edge(options=options)
browser.maximize_window()                        #最大化窗口
browser.get( [link] )                            # link_target为目标网页的网址的字符串
browser.implicitly_wait(2)                       # 等待一段时间使网页打开
time.sleep(2)                                    # 这里是用time.sleep()可能更有效

browser.page_source    #返回网页的代码,可以和beautifusoup包搭配使用

Step3:查找特定元素

在edge浏览器中可以在网页中对目标点击:右键--检查,查看网页源码,从而锁定目标查询并互动。

selenium提供八种查找方式,其中:"XPATH"和"CSS_SELECTOR",可以在网页源码"元素"栏点击:右键--"复制XPath"和"复制selector"获得。其余的可以在元素栏中找到

复制代码
from selenium.webdriver.common.by import By  # 新版selenium使用By实现元素检索

browser.find_element(By.XPATH, [str])
browser.find_element(By.CSS_SELECTOR, [str])
browser.find_element(By.ID, [str])
browser.find_element(By.TAG_NAME, [str])
browser.find_element(By.CLASS_NAME, [str])
browser.find_element(By.PARTIAL_LINK_TEXT, [str])
browser.find_element(By.LINK_TEXT, [str])
browser.find_element(By.NAME, [str])

Step4:常见元素的互动方式

复制代码
# 4-1 : Anchor链接类型
# 例如:<a href="#" class="zdy-btn zdy-btn-cur">查询<em></em></a>
# 注释:其中href是链接地址,使用:.click()点击
# 发现:有些网页使用By.LINK_TEXT更好用

browser.find_element(By.LINK_TEXT, '查询').click()

# 4-2 : input文本框类型
# 例如:<input type="text" class="ipt-sc issueFrom" title="">
# 注释:使用:.send_keys()填写
# 发现:如出现经常匹配不到的情况,可以增加等待时间,或者用try配合多种匹配方法

browser.find_element(By.XPATH, r'//*[@id="notie"]/body/strong/strong/div[6]/div[2]/ul/li[5]/div/div/div[2]/div[2]/p[1]/input[1]').send_keys( [str] )
相关推荐
小白学大数据14 小时前
构建企业级Selenium爬虫:基于隧道代理的IP管理架构
爬虫·tcp/ip·selenium
华科云商xiao徐16 小时前
详解Selenium爬虫部署七大常见错误及修复方案
爬虫·selenium
别来无恙14919 小时前
使用Python和Selenium进行Web自动化测试:从入门到实践
selenium·测试工具
Python大数据分析@19 小时前
python用selenium怎么规避检测?
开发语言·python·selenium·网络爬虫
ThreeAu.19 小时前
Miniconda3搭建Selenium的python虚拟环境全攻略
开发语言·python·selenium·minicoda·python环境配置
测试老哥1 天前
6个步骤实现Postman接口压力测试
自动化测试·软件测试·测试工具·测试用例·接口测试·压力测试·postman
北岛三生2 天前
ISP(图像信号处理器)
图像处理·数码相机·测试工具·计算机视觉·测试用例·模块测试
北岛三生3 天前
Camera tuning flow相机调试流程
图像处理·数码相机·测试工具·模块测试