加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
kdriver.py 2.03 KB
一键复制 编辑 原始数据 按行查看 历史
zhangk 提交于 2021-01-10 21:52 . action extends kdriver
import pickle
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By as seleniumBY
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as seleniumEC
from info import Info
class Kdriver:
def __init__(self):
driver = webdriver.Chrome(executable_path=Info.driver_path)
driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
'source': '''
Object.defineProperty(navigator, 'webdriver', {
get: () => undefined
})
'''
})
self.driver = driver
# def wait_element_load(self, element, expiration_time=10, **keywargs):
# while not self.is_exist(element, **keywargs):
# expiration_time -= 2
# if expiration_time < 0:
# return False
# sleep(2)
# return True
def wait_element_load(self, element, expiration_time=10, **kwargs):
try:
WebDriverWait(self.driver, expiration_time)\
.until(seleniumEC.presence_of_element_located((seleniumBY.CSS_SELECTOR,element)))
except TimeoutError:
return False
if len(kwargs) > 0:
return self.is_exist(element, **kwargs)
return True
def is_exist(self, element, **keywargs):
flag = True
try:
target_element = self.driver.find_element_by_css_selector(element)
if len(keywargs) > 0:
for k,v in keywargs.items():
if getattr(target_element,k) != v:
raise NoSuchElementException
return flag
except NoSuchElementException:
flag = False
return flag
def load_cookie(self, cookie):
self.driver.delete_all_cookies()
with open(Info.cookie_path, 'rb') as ck:
cookies = pickle.load(ck)
for cookie in cookies:
self.driver.add_cookie(cookie)
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化