13.1 反射
# 什么是反射?
# 如果有一个变量名,是字符串的数据类型,你能获取到这个变量的值吗?
# 反射方法:
class Student:
def __init__(self):
self.name='张三'
self.age='18'
self.gender='男'
stu=Student()
print(stu.name)
content=input('>>>')
if content=='name':
print(stu.name)
msg=getattr(stu,content)
print(msg)
has=hasattr(stu,content)
print(has)
if has:
msg=getattr(stu,content)
print(msg)
对象反射:
hasattr(对象,属性名) 判断对象是否有这个属性,有返回True
getattr(对象,属性名) 返回对象中属性名对应的值
13.2selenium键盘事件
反射方法:
class Student:
def __init__(self):
self.name = '张三'
self.age = '18'
self.gender = '男'
@property
def show_info(self):
print(1111)
return 222222
def get_student(self):
print('学生的数量')
stu=Student()
stu.show_info
content=input('>>>')
has=hasattr(stu,cotent)
print(has)
第一种用property伪类装饰器
if has:
ret=getattr(stu,content)
print(ret)
第二种方式
if has:
ret=getattr(stu,content)
if callable(ret):
ret()
else:
print(ret)
类的反射
class A:
role='男'
print(A.role)
用类名反射获取类的变量
print(getattr(A,'role'))
# 模块的反射:
import time
print(time.time())
print(time.time)
print(getattr(time,'time'))
ret=getattr(time,'time')()
print(ret)
对象反射
# hasattr(对象,属性)判断对象是否有这个属性,有返回true
# getattr(对象,属性名)
import time
from selenium import webdriver
from selenium.webdriver.common.keys import keys
from selenium.webdriver.common.by import By
driver=webdriver.Chrome()
driver.get('http://www.baidu.com')
driver.maximize_window()#最大化浏览器窗口
time.sleep(3)
input_obj=driver.find_element_by_id('kw')
input_obj.send_keys('爱软测')
#全选:
input_obj.send_keys(Keys.CONTROL,'a')
time.sleep(2)
#复制
input_obj.send_keys(Keys.CONTROL,'c')
time.sleep(2)
input_obj.clear()
time.sleep(2)
#粘贴
input_obj.send_keys(Keys.CONTROL,'v')
time.sleep(3)
driver.close()
13.3文件上传
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
driver=webdriver.Chrome()
driver.get('http://47.107.57.201:9000/api/upload/2')
driver.maximize_window()#最大化浏览器窗口
time.sleep(1)
driver.find_element(By.ID,'ajaxFile').send_keys(r'D:\Backup\桌面\接口导入模板(session)-薄杰 - (1).xls')
time.sleep(1)
driver.find_element(By.ID,'ajaxBtn').click()
13.4滚动条操作
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
driver=webdriver.Chrome()
driver.get('http://47.107.57.201:9000/api/upload/2')
driver.maximize_window()#最大化浏览器窗口
time.sleep(1)
driver.find_element(By.ID,'ajaxFile').send_keys(r'D:\Backup\桌面\接口导入模板(session)-薄杰 - (1).xls')
time.sleep(1)
driver.find_element(By.ID,'ajaxBtn').click()
13。5 鼠标事件
import time
from selenium import webdriver
from selenium.webdriver import ActionChains
driver=webdriver.Chrome()
# driver.get('https://www.cnblogs.com/TodayWind/category/1989473.html')
# driver.maximize_window()
# time.sleep(1)
#鼠标悬浮
ActionChains(driver).move_to_element(driver.find_element_by_link_text('联系')).perform()
time.sleep(3)
driver.close()
#鼠标拖拽
# driver.get('https://www.jq22.com/demo/pintu20151229/')
# driver.maximize_window()
# time.sleep(1)
# driver.find_element_by_id('start').click()
# time.sleep(1)
# div_lst=driver.find_element_by_css_selector('div[id=container] div')
# print(div_lst)
# start=div_lst[0]
# end=div_lst[-1]
# time.sleep(1)
# ActionChains(driver).drag_and_drop(start,end).perform()
# time.sleep(3)
# driver.close()
#鼠标单击
# driver.get('https://www.jq22.com/demo/pintu20151229/')
# driver.maximize_window()
# time.sleep(1)
# ActionChains(driver).double_click(driver.find_element_by_id('start')).perform()
#鼠标左键双击
# ActionChains(driver).double_click(driver.find_element_by_id('start')).perform()
#鼠标右键单击
# driver.get('https://www.jq22.com/demo/pintu20151229/')
# driver.maximize_window()
# time.sleep(1)
# ActionChains(driver).context_click(driver.find_element_by_link_text('联系')).perform()
# time.sleep(2)
# driver.close()
13.6 验证码
from selenium import webdriver
import time
from ddddocr import Ddddocr
driver=webdriver.Chrome()
driver.get('https://so.gushiwen.cn/user/login.aspx?from=http://so.gushiwen.cn/user/collect.aspx')
driver.maximize_window()
driver.find_element_by_id('email').send_keys('111111')
time.sleep(0.5)
driver.find_element_by_id('pwd').send_keys('2222')
time.sleep(3)
driver.find_element_by_id('imgCode').screenshot('古诗文.png')
ocr=Ddddocr()
with open('古诗文.png','rb')as f:
img_content=f.read()
result=ocr.classification(img_content)
print(result)
driver.find_element_by_id('code').send_keys(result)
time.sleep(3)
13.7 等待机制
# 1.现实等待:针对某一元素,在设置时间内,默认每隔一段时间检测一下当前页面的这个元素是否存在,如果超过时间检测不到,就会报异常
# 2.隐式等待:针对全局元素,在浏览器创建之初,在渲染标签元素的时候,我们可以加上隐式等待
# 3.强制等待:time.sleep()
from selenium import webdriver
import time
from selenium.webdriver.support import expected_conditions as ES
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
driver=webdriver.Chrome()
driver.get('http://www.cnblogs.com/TodayWind/p/14903631.html')
driver.implicitly_wait(30)#隐式等待:
wait=WebDriverWait(driver,timeout=10,poll_frequency=0.5)
wait.until(ES.visibility_of_element_located((By.LINK_TEXT,'博客园'))).click()
# timeout 设置超时时间
# poll_frequency 设置每多少秒去检测一下当前元素
# ignored_exceptions 忽略异常
# until 当元素出现,条件成立时,则继续进行
# until_not 当元素不出现,条件不成立时,则继续执行
#
# time.sleep(3)
driver.close()
13.8无头模式
from selenium import webdriver
#谷歌无头
from selenium.webdriver.chrome.options import Options
#创建一个参数对象,用来控制Chrome以无界面模式打开
Chrome_options=Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
#创建浏览器对象
driver=webdriver.chrome(chrome_options=chrome_options)
driver.implicitly_wait(30)
#访问url
driver.get('http://www.baidu.com')
print(driver.title)#百度一下,你就知道
print(driver.current_url)
driver.quit()
#火狐无头
from selenium.webdriver.firefox.options import Options
#创建浏览器对象
options=Options()
options.add_argument('-headless')
driver=webdriver.Firefox(options=options)
driver.implicitly_wait(30)
#访问url
driver.get('http://www.baidu.com')
print(driver.title)#百度一下,你就知道
driver.quit()
13.9pom设计模式
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.select import Select
from selenium.common.exceptions import NoSuchElementException, NoSuchFrameException, TimeoutException, \
NoAlertPresentException
class BasePage:
"""基类,把selenium公共方法进行二次封装"""
def __init__(self, driver):
self.driver = driver
def find_element(self, method, element):
"""查找元素"""
try:
fe = self.driver.find_element(method, element)
return fe
except NoSuchElementException as e:
print('未找到元素', e)
def my_send_keys(self, method, element, text):
'''输入'''
fe = self.find_element(method, element)
if fe:
try:
fe.send_keys(text)
except Exception as e:
print('输入有误!!')
def my_click(self, method, element):
try:
fe = self.find_element(method, element)
if fe:
fe.click()
except Exception as e:
print('点击报错')
def wait(self, seconds):
# 静态等待
self.driver.implicitly_wait(seconds)
def display_wait(self, method, element):
# 显示等待
try:
WebDriverWait(driver=self.driver, timeout=10, poll_frequency=0.5).until(
ec.visibility_of_element_located((method, element)))
except TimeoutException as exception_msg:
print('显示等待超时,显示等待未找到该元:', exception_msg)
def switch_to_window(self):
# 切换到新打开的窗口
handle = self.driver.current_window_handle
for handle_ in self.driver.window_handles:
if handle != handle_:
self.driver.switch_to.window(handle)
else:
raise ValueError("未找到标题为的页面") # 主动抛异常
else:
self.driver.switch_to.window(self.driver.window_handles[-1])
def switch_to_frame(self, iframe_element, status: bool = False):
if iframe_element:
self.driver.switch_to.frame(iframe_element)
else:
if status:
# 切换到主页面
self.driver.switch_to.default_content()
else:
self.driver.switch_to.parent_frame()
def forward(self):
# 前进
self.driver.forward()
def back(self):
# 回退
self.driver.back()
def refresh(self):
# 刷新
self.driver.refresh()
def close(self):
# 关闭当前窗口
self.driver.close()
def quit(self):
# 退出驱动,关闭所有相关的窗口
self.driver.quit()
def my_sleep(self, num):
time.sleep(num)
def move_execute_script(self, web_test_data=None):
"""滚动进度条"""
# 获取当前的窗口对象
element = self.driver.find_element(By.TAG_NAME, 'body')
if web_test_data:
if web_test_data.lower() == 'ture':
# 从底部拉到顶部
self.driver.execute_script("arguments[0].scrollIntoView(true);", element)
time.sleep(0.5)
elif web_test_data.lower() == 'false':
# 从顶部拉到底部
self.driver.execute_script("arguments[0].scrollIntoView(false);", element)
else:
# 相对移动, 从当前位置移动web_test_data像素
self.driver.execute_script('window.scrollBy(0,%s)' % web_test_data, )
else:
return '缺少测试数据web_test_data'
def move_to_element(self, method, element):
"""鼠标悬停"""
el = self.driver.find_element(method, element)
ActionChains(self.driver).move_to_element(el).perform()
time.sleep(0.5)
class SeleniumHandler(BasePage):
"""业务层"""
def __init__(self, driver):
super().__init__(driver)
driver.get('https://www.baidu.com')
def test_search(self):
method1, ele2 = (By.ID, 'kw')
method2, ele3 = (By.ID, 'su')
self.my_send_keys(method1, ele2, 'selenium真好用!!!')
self.my_sleep(2)
self.my_click(method2, ele3)
driver = webdriver.Chrome()
sh = SeleniumHandler(driver)
sh.test_search()
13.10 绕过二维码
import time标签:selenium,self,driver,验证码,element,滚动条,time,import,设计模式 From: https://www.cnblogs.com/zhh0125/p/16667018.html
import random
from selenium import webdriver
from selenium.webdriver.common.by import By
class WX:
def __init__(self):
self.user_argument1 = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36'
self.user_argument2 = 'MQQBrowser/26 Mozilla/5.0 (Linux; U; Android 2.3.7; zh-cn; MB200 Build/GRJ22;CyanogenMod-7) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1'
self.options = webdriver.ChromeOptions()
self.options.add_argument('user-agent=%s' % self.user_argument1)
self.driver = webdriver.Chrome(chrome_options=self.options)
self.driver.get('https://work.weixin.qq.com/wework_admin/frame')
cookie_dict = {
"RK": "/Phs2XUDPQ",
"ptcz": "bbc0c092e7450a1449e6e7719599f27d71a994fbd61fd7a1e75d9c0f70f44a29",
"pgv_pvid": "6127127366",
"tvfe_boss_uuid": "a845f7b21688a6e9",
"pgv_pvi": "1084163072",
"iip": "0",
"pac_uid": '1_154439155',
"wwrtx.i18n_lan": 'zh',
"wwrtx.c_gdpr": '0',
"wwrtx.ref": "direct",
"wwrtx.refid": "01794903",
"wwrtx.d2st": "a3118983",
"wwrtx.sid": "AtBSMo3TBCnpmym5yvwy5vPyy9p28vgEkZsadZXgnUkjfT_KlhK-PvJKHmZtnfDT",
"wwrtx.ltype": '1',
"wwrtx.vst": "wyIoLFbxbqip4EKcbLqph547_s4bpj7uwLFLFmrsEGG7PHLkrVNkNdUsL4EoNulnLr5bTCZXYG_N1ngxtd4oBRk4LerkawOyt7rffLOWKXTGTUj6i0MhYJjxdeQy1yAtyYkGWVuYUTSQfKezbuvYXuUYRnNgXSVeX4zhnpqRtg2SYpounHOs5iCrx74yKpP1kQXnEG_D-9r0Cf7BA3pttZINpA-VrIl0Jy9oAG40kqtiNlf0kb8aqoIyG7Xq2YNEQKb3cWxOv9yoKPcyA1tUZQ",
"wwrtx.vid": "1688855804348075",
"wxpay.corpid": "1970326358988015",
"wxpay.vid": "1688855804348075",
"wwrtx.cs_ind": "",
"wwrtx.logined": "true"
}
[self.driver.add_cookie({'name': k, 'value': v}) for k, v in cookie_dict.items()]
self.driver.get('https://work.weixin.qq.com/wework_admin/frame')
self.driver.maximize_window()
self.driver.implicitly_wait(30)
time.sleep(10)
WX()
"""
RK=/Phs2XUDPQ;
ptcz=bbc0c092e7450a1449e6e7719599f27d71a994fbd61fd7a1e75d9c0f70f44a29;
pgv_pvid=6127127366;
tvfe_boss_uuid=a845f7b21688a6e9;
pgv_pvi=1084163072;
iip=0;
pac_uid=1_154439155;
wwrtx.i18n_lan=zh;
wwrtx.c_gdpr=0;
wwrtx.ref=direct;
wwrtx.refid=01794903;
wwrtx.ltype=1;
wwrtx.vid=1688855804348075;
wxpay.corpid=1970326358988015;
wxpay.vid=1688855804348075;
wwrtx.d2st=a3118983;
wwrtx.sid=AtBSMo3TBCnpmym5yvwy5vPyy9p28vgEkZsadZXgnUkjfT_KlhK-PvJKHmZtnfDT;
wwrtx.vst=wyIoLFbxbqip4EKcbLqph547_s4bpj7uwLFLFmrsEGG7PHLkrVNkNdUsL4EoNulnLr5bTCZXYG_N1ngxtd4oBRk4LerkawOyt7rffLOWKXTGTUj6i0MhYJjxdeQy1yAtyYkGWVuYUTSQfKezbuvYXuUYRnNgXSVeX4zhnpqRtg2SYpounHOs5iCrx74yKpP1kQXnEG_D-9r0Cf7BA3pttZINpA-VrIl0Jy9oAG40kqtiNlf0kb8aqoIyG7Xq2YNEQKb3cWxOv9yoKPcyA1tUZQ;
wwrtx.cs_ind=;
wwrtx.logined=true
"""