selenium安装与配置与操作
selenium是一个web端自动化测试框架,可以通过代码来控制浏览器,比如打开关闭,点击等行为
作用:帮助抓取动态加载的数据,避免反爬
安装:
1.Chrome浏览器
2.selenium框架:pip install selenium
3.驱动程序:下载
http://npm.taobao.org/mirrors/chromedriver/
查看浏览器版本
选择对应的版本
编码流程:
#首先需要将下载的chromedriver.exe放到代码文件夹下
#导包
from seleniumi import webdriver
#调用chromedriver.exe
bro = webdriver.Chrome('./chromedriver.exe')
#访问
bro.get('https://www.iqiyi.com/')
#获取网页源代码
(对象)bro.page_source --->字符串
#如何获取网页的元素
#根据标签内属性定位,一般用id定位
find_element_by_id('id')
find_element_by_name('name')
find_element_by_class_name('class')#根据class属性定位
find_element_by_xpath()#根据xpath定位节点
find_element_by_css_selector()#css选择器
find_element_by_link_text()#根据超链接文本定位
find_element_by_partial_link_text()#根据超链接文本的一部分定位
#节点交互操作:
1.输入内容:对象.send_keys()
2.清空内容:对象.clear()
3.点击操作:对象.click()
4.退出浏览器:对象.quit()
#执行js脚本
js = 'window.scrollTo(0,300)'#向下滚动300距离
js = 'window.scrollTo(0,document.body.scrollHeight)'#滚动到底部
对象.execute_script(js)
from selenium import webdriver
from time import sleep
from selenium.webdriver.chrome.options import Options
options = Options()
options.add_experimental_option('excludeSwitches',['enable-automation'])
#调用chromedriver.exe
bro = webdriver.Chrome('./chromedriver.exe',options=options)
bro.get('https://www.baidu.com/')
#根据id-->kw获取input输入框
input_tag = bro.find_element_by_id('kw')
#根据id-->su获取百度一下点击按钮
button_baidu = bro.find_element_by_id('su')
#输入框输入
input_tag.send_keys('黑洞')
#点击
button_baidu.click()
#睡眠两秒之后清空输入框
sleep(2)
input_tag.clear()
input_tag.send_keys('抖动')
button_baidu.click()
sleep(3)
input_tag.clear()
input_tag.send_keys('翻转')
button_baidu.click()
sleep(3)
input_tag.clear()
bro.quit()
子级页面和父级页面
#子页面的跳转
switch_to.frame('id')
#跳转到父级页面
switch_to_default.conent()
防检测
from selenium.webdriver.chrome.options import Options
options = Options()
options.add_experimental_option('excludeSwitches',['enable-automation'])
bro = webdriver.Chrome('./chromedriver.exe',options=options)
本文详细介绍Selenium自动化测试框架的安装、配置及操作流程,包括Chrome浏览器驱动的使用,通过Python代码实现网页的自动化操作,如打开网页、查找元素、执行JS脚本等,适用于动态网页数据抓取和自动化测试。
1万+

被折叠的 条评论
为什么被折叠?



