- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
标题说明了一切 - 我正在寻找一种方法(或多种方法)来加载、启用、添加(以及同样地:禁用/删除)扩展 webdriver 已创建。
上下文:Python、selenium(每个标签)。某些部分的 Pyautogui 是不可避免的,但需要健壮。我有一个工作解决方案草案,但它粗糙且有点依赖 GPU(要点:可以/不会接受“这不能用 Chrome 完成”,因为我知道它可以完成,但希望看到一些解决方案/代码达到这个效果).
我完全了解在实例化/创建驱动程序之前加载扩展的各种方法。即
其中 o = 选项,profileX 已预安装扩展等。所以很明显 - 我对这种效果的提案完全不感兴趣。
关于标题/上面的问题有什么想法/建议吗?
理想情况下(但并非绝对重要)是一种不完全基于 GUI(依赖于机器人/PyAutogui)的编程解决方案。
对于此练习,您可以假设该扩展程序在 chrome 商店中可用。
用例:我正在测试的扩展涉及注册点和保护公平/预期使用条款,它被设计为在识别自动操作时停止运行(这对于“有头”的 chrome 来说是完全可能的,例如你只需分配它是 chrome 设置中的热键,并使用 Pyautogui 激活,或者定位它的 html 页面并直接交互等)。考虑到这一点,以及我进行的非常多的测试,我不得不重新加载测试、设置配置文件或经常停止和启动测试,以便我可以包含"new"副本,这似乎是一种资源浪费crx 文件或部署我上面提到的其他方法之一。迄今为止/据我所知,没有解决方案。如果有人能指出我在这方面的“重复”问题,我很高兴感到惊喜。
最佳答案
import glob2,itertools,os, pyautogui, shutil, time, pyperclip, subprocess, keyboard as kb
from datetime import datetime
from zipfile import ZipFile
now = datetime.now()
dt_string: str = now.strftime("%d-%b-%Y, %H:%M:%S")
print(dt_string)
from selenium import webdriver
from selenium.webdriver import DesiredCapabilities
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.wait import WebDriverWait
from concurrent.futures import ThreadPoolExecutor
from os import path
#references: date-time format: https://www.programiz.com/python-programming/datetime/current-datetime
方法一:在 chrome 启动后通过 Chrome-store 添加
def ext_update_method1(ps, section=''):
global w, p2s
text_temp, p2s = [''] * len(ps), []
def button_click(p, parms = ['',True]):
#parms[0] = ID, parms[1] = click?
ID,click = parms[0], parms[1]
global text_temp
text_temp[p] = ''
ID = ['omghfjlpggmjjaagoclmmobgdodcjboh'] if ID == '' else ID #default i= Browsec if no ID entered
d[p].get(f'https://chrome.google.com/webstore/detail/{ID[0]}')
w[p] = WebDriverWait(d[p], 10)
w[p].until(lambda x: x.execute_script("return document.readyState") == "complete")
button = w[p].until(lambda x: x.find_element_by_class_name('g-c-R'))
text_temp[p] = button.text
if click == True: button.click()
def add_remove():
global p2s
for i, y in enumerate(ys): activ(i, ys), (ss, 0.5), keys([(pr, 'tab'), (pr, 'space')])
after2, ys2 = gwwt(''), []
for x in after2:
if (x not in before) and (x not in ys_remove): ys2 = ys2 + [x, ]
# ys2 = ys2 + [x,] if (all(x not in before) and (x not in ys_remove)) else ys2
for i, y in enumerate(ys2): activ(i, ys), (ss, 0.5), keys([(pr, 'tab'), (pr, 'space')])
ss(1)
after2, ys2 = gwwt(''), []
for x in after2:
if (x not in before) and (x not in ys_remove) and (x not in a[0] for a in wd): ys2 = ys2 + [x, ]
for i, y in enumerate(ys2):
if all(y != x[0] for x in wd): y.close()
if len(ys_remove) > 0:
for i, y in enumerate(ys_remove):
activ(i, ys_remove), pr('space'), ss(0.5)
p2s = p2s + [i, ]
if section == 1:
return 'complete 2nd iteration' #prevent endless loop (see next comment)
else:
print('removed add-in, now adding back again....')
cc(2)
thread_all(ps, close_extra)
ext_update_method1(p2s, 1) #loop back on self to add
else:
return 'complete 1st iteration'
def close_extra(p):
global w
w_old = w[p]
w[p] = WebDriverWait(d[p], 10)
tabs_close_extra(p)
tabs_close_extra(p)
activ(p), pr('a'), activ(p), pr('enter')
w[p].until(lambda x: x.execute_script("return document.readyState") == "complete")
w[p] = w_old
thread_all(ps, tabs_close_extra)
before = gwwt('')
thread_all(ps, button_click)
cc(2) #cc(5)
after = gwwt('')
ys, ys_remove, p2s = [], [], []
ys_remove = gwwt('remove')
print(f'ys_remove = {ys_remove}')
for x in after:
if (x not in ys_remove) and (x not in before): ys = ys + [x, ]
print(add_remove())
cc(2)
thread_all(ps, close_extra)
thread_all(ps,button_click,['',False])
qs = []
for x in text_temp: qs = qs + [1,] if 'add' in x.lower() else qs
print(f'qs: {qs}')
if section == 2: return #prevent never-ending loop (see next comment)
if len(qs) > 0: ext_update_method1(qs,2) #loop back on self in case 'add extension' still present in web-store
注意事项:可以在同一个浏览器上下载同一个扩展的多个版本
n_i_c[0]
= 您希望下载给定的次数扩展到同一个浏览器n_i_c[1]
= 全局列表项:ext_details,参见 vars()n_i_c 2 =1 清除文件夹n_i_c[3]
= 0 => 只下载解压的文件夹(不加载它)方法 2:Chrome 启动后下载并加载 .crx 文件
def ext_update_method2(ps, n_i_c=[2, 0, 1,1], section = ''): # same order as it would
appear for single set of extensions (iro one tab)...
# parms = [2,0,0,0] =>
# 0. repetitions - e.g. 2 downloads : uBlock
# 1. 0 [index value - e.g. uBlock = 4, below] downloaded and unzipped/installed on profile p
# 2: clear folder
# 3: is_load = 0 => only download unpacked folder (not loading it too)
global start, w, files_old, ev, d, parent, txt
global tabs_before
global files, files_new, index_latest_files, index_redo, index_hks
hks2, index_ext, clear_folder, is_load = n_i_c[0], n_i_c[1], n_i_c[2], n_i_c[3] # ID, alias = cred[0], cred[1], cred[2]
hks2 = hks if hks == '' else hks2
ID, alias = ext_details[index_ext][1], ext_details[index_ext][0]
url_robwu = '''https://robwu.nl/crxviewer/?crx=https://chrome.google.com/webstore/detail/''' + str(ID)
if clear_folder == 1:
folder_clear(del_dir=os.path.join(os.path.expanduser("~"), 'Downloads', '*'))
def thread_all_0(p): #set up stuff
global d, w, index_hks2
if 'error' in str(tabs_close_extra(p)):
tab_close(p)
d[p].implicitly_wait(5)
w[p] = WebDriverWait(d[p], 5)
index_hks2[p] = ''
d[p].get('chrome://extensions')
code_0 = '''var tags = document.querySelector('body').querySelector('extensions-manager')['shadowRoot'].querySelector('cr-view-manager').querySelector('extensions-item-list')["shadowRoot"].querySelector('#container').querySelectorAll('extensions-item'); return tags.length;'''
index_hks[p]=ev[p](code_0)
print(index_hks[p])
#
thread_all(ps, thread_all_0)
#
def thread_all_1(p): #open website to download crx (multi-thread to expedite)
d[p].get(url_robwu)
#
if len(ps) >= 2: #prevent overloading website - only do 3 at a time if more than 2 browsers being used
groups = list(data_mygrouper(2, ps))
for x in groups: thread_all(x, thread_all_1,workers = 3, chunk = 3)
else:
thread_all(ps, thread_all_1)
files_old = glob2.glob(os.path.join(os.path.expanduser("~"), 'Downloads', '*.zip'))
def thread_all_2(p):
try:
w[p].until(lambda x: x.find_element_by_id("download-link")).click()
print('lambda wait passed !!')
except:
print('lambda wait failed :(')
return
start_temp = time.time()
while (time.time() - start_temp <= 90) and (len(glob2.glob(os.path.join(os.path.expanduser("~"), 'Downloads', '*.zip'))) - len(files_old) < hks2 * (len(ps))) or (kb.is_pressed('escape') == True):
if kb.is_pressed('escape') == True: break
thread_all(ps, thread_all_2), ss(1)
files = glob2.glob(os.path.join(os.path.expanduser("~"), 'Downloads', '*.zip'))
files_new = []
for keep in files:
if str(keep) not in files_old: files_new = files_new + [str(keep), ]
# thread_all(files_new, z_extension_unzip, alias)
path_dir_core = os.path.join(os.path.expanduser("~"), 'Downloads')
index_latest_files = [''] * len(files_new)
#
def thread_all_3(j): # unzip
global index_latest_files
index_latest_files[j] = os.path.join(path_dir_core, alias + str(j))
with ZipFile(files_new[j], 'r') as zipObj:
zipObj.extractall(index_latest_files[j])
os.remove(files_new[j])
#
thread_all(list(range(len(files_new))), thread_all_3)
if is_load != 1: return
code1 = '''if(document.querySelector('body').querySelector('extensions-manager')["shadowRoot"].querySelector('extensions-toolbar').attributes.length !=2){document.querySelector("body").querySelector("extensions-manager")["shadowRoot"].querySelector("extensions-toolbar")["shadowRoot"].querySelector("cr-toolbar").querySelector(".more-actions").querySelector("#devMode")["shadowRoot"].querySelector("#knob").click() } else {'dev mode already activated!'}'''
code2 = '''document.querySelector('body').querySelector('extensions-manager')["shadowRoot"].querySelector('extensions-toolbar')["shadowRoot"].querySelector("#loadUnpacked").click()'''
#
def thread_all_4(p):
d[p].get('chrome://extensions/'), ss(1)
ev[p](code1)
for y in range(hks2):
thread_all(ps, thread_all_4)
windows_before = gwwt('Select the extension directory')
for p in ps:
try:
if path.exists(os.path.join(path_dir_core, index_latest_files[p + len(ps) * (y)])):
try:
ev[p](code2)
except:
continue
start_temp = time.time()
while (time.time() - start_temp <= 30) and (
len(gwwt('Select the extension directory')) - len(windows_before)) < 1 and (
'select the extension directory' not in gawt().lower()): pass # len(ps) - len(errors_chrome()): pass
tabs_before = len(d[p].window_handles)
windows_A = gwwt('')
try:
keys([(tw, index_latest_files[p + len(ps) * (y)]), (ss, 0.5), (pr, 'enter'), (pr, 'tab'),(pr, 'space')], 0.75)
if len(windows_A) < len(gwwt('')):
d[p].refresh()
print('would break1')
else:
window_target = gwwt('Select the extension directory')[0]
try:
window_target.activate()
except:
window_target.minimize()
window_target.restore()
finally:
pyperclip.copy(index_latest_files[p + len(ps) * (y)]), ss(0.5)
keys([(hk, 'ctrl', 'l'), (kd, 'shift'), (pr, 'tab', 4), (ku, 'shift'), (hk, 'ctrl', 'v'), (pr, 'enter'), (pr, 'tab'), (pr, 'space')])
except:
d[p].refresh()
pr('escape', 2)
print('would break2')
tabs_close_extra(p)
else: continue
except: continue
def thread_all_5(p):
global qs
d[p].get('chrome://extensions/shortcuts')
code_0 = '''return document.querySelector('body').firstElementChild["shadowRoot"].querySelector("cr-view-manager").querySelector('extensions-keyboard-shortcuts')['shadowRoot'].querySelector('#container').querySelectorAll('.shortcut-card').length'''
index_hks[p] = int(ev[p](code_0)) - index_hks[p]
qs = qs + [p,] if index_hks[p] < hks2 else qs
print(f'index_hks[{p}] = {index_hks[p]}')
index4[p] = 0
qs = []
if clear_folder == 1:
thread_all(ps, thread_all_5)
if section == 1: return
if len(qs) > 0: ext_update_method2(qs, n_i_c = [hks2, index_ext, 0, 1], section = 1)
qs = []
for p in range(len(ps)): qs = qs + [p,]
方法 3:以编程方式删除
def ext_remove(ps,ext):
for p in range(len(ps)):
try:
activ(p)
d[p].get('chrome://extensions/')
#pr('f12'),ss(1)
hk('ctrl', 'shift', 'j'), ss(1)
code = '''var tags = document.querySelector('body').querySelector('extensions-manager')['shadowRoot'].querySelector('cr-view-manager').querySelector('extensions-item-list')["shadowRoot"].querySelector('#container').querySelectorAll('extensions-item'); for (i = 0;i <= tags.length; i ++) {try {if(tags[i]['shadowRoot'].querySelector('#a11yAssociation').innerText.toLowerCase().indexOf("''' + str(ext) +'''") > 0) {tags[i]['shadowRoot'].querySelector('#remove-button').click();break} } catch {}}'''
pyperclip.copy(code), ss(0.5)
# pr('tab'), ss(0.5)
temp_rep = 1 if type(ext) == str else len(ext)
for _ in range(temp_rep):
hk('ctrl', 'v'), ss(0.5)
pr('enter'), ss(0.5)
pr('space'), ss(0.5)
tabs_close_extra(p)
pr('f12'), ss(0.5) #hk('ctrl', 'shift', 'j'), ss(0.5)
except: pass
*(包含 java 脚本 - 保存在与此脚本相同的位置
激活窗口
pyautogui.FAILSAFE = False
def activ(p, index_wd=''):
global index_activ
try:
if index_wd == '':
index_wd = wd[p][0]
else:
index_wd = index_wd[p]
except:
index_wd = wd[p]
print(f'active {w}')
index_activ[p] = False
try:
index_wd.activate()
index_activ[p] = True
return index_activ[p]
except:
try:
index_wd.minimize()
index_wd.restore()
index_activ[p] = True
return index_activ[p]
except:
index_activ[p] = False
index_activ[p] = False
return index_activ[p]
快捷键
def keys(actions, delay=0.5):
# global BL3
print(f'def keys()') # {actions}') #, profile {p}')
outcome = []
for action in actions:
print(f'action {action}')
if len(action) == 4:
outcome = outcome + [action[0](action[1], action[2], action[3]), ]
elif len(action) == 3:
outcome = outcome + [action[0](action[1], action[2]), ]
elif (len(action) == 2) and (action[1] != ''):
outcome = outcome + [action[0](action[1]), ]
else:
outcome = outcome + [action[0](), ]
ss(delay) # await ass(delay)
return outcome
分割列表
def data_mygrouper(n,
iterable):
args = [iter(iterable)] * n
return ([e for e in t if e != None] for t in itertools.zip_longest(*args))
堆栈溢出引用(data_mygrouper)
线程池
def thread_all(ps, fn, parm='', actions=[], workers=6, chunk=1):
# https://stackoverflow.com/questions/42056738/how-to-pass-a-function-with-more-than-one-argument-to-python-concurrent-futures/42056975
print(f'thread_all({ps}, {fn}, {parm}, {actions}')
if parm == '':
with ThreadPoolExecutor(max_workers=max(1, workers)) as executor:
return executor.map(fn, ps, timeout=90, chunksize=max(1, chunk))
else:
with ThreadPoolExecutor(max_workers=max(1, workers)) as executor:
return executor.map(fn, ps, itertools.repeat(parm, L), timeout=90, chunksize=max(1, chunk))
线程池执行器引用:here
关闭标签页
def tab_close(p):
print(f'def tab_close {p}')
# d[p].switch_to.window(parent[p])
for h in d[p].window_handles:
d[p].switch_to.window(h)
parent[p] = h
[ev[p]] = [d[p].execute_script]
break
# parent[p] = d[p].current_window_handle
for h in d[p].window_handles:
if h != parent[p]:
d[p].switch_to.window(h)
if len(d[p].window_handles) > 1: d[p].close()
else: break
d[p].switch_to.window(parent[p])
def tabs_close_extra(p):
# alternative method (much slower): https://stackoverflow.com/questions/12729265/switch-tabs-using-selenium-webdriver-with-java
try:
for h in d[p].window_handles:
d[p].switch_to.window(h)
parent[p] = h
break
# parent[p] = d[p].current_window_handle
tabs_original = len(d[p].window_handles)
if tabs_original > 1:
for h in d[p].window_handles:
if h != parent[p]:
d[p].switch_to.window(h)
activ(p), hk('ctrl', 'w')
if len(d[p].window_handles) == tabs_original:
d[p].close()
# d[p].switch_to.window(parent[p])
d[p].switch_to.window(parent[p])
except:
print(f'error in tabs_close_extra {p}')
变量
def vars():
print('def vars()')
global index, index2, index3, index4, index5, index6
global index_activ, index_activ2, hks, pycharm_win
global index_latest_files, index_hks, index_hks2
global parent, d, w, w2
global path_chrome, path_exec, path_core, path_temp, profile, done, caps, pycharm_win
global ps, p2s, qs
global L, tile_type, compact, outcome
global kd, ku, hk, pr, tw, wr, cl
global gats, gaws, gwwt, gawt, gaw
global cc, ss, start, start2, start_overall
global wd, wd2, ev, errors, errors2, errors3
global ext_0, ext_1, ext_2, ext_3,ext_details
caps = DesiredCapabilities.CHROME.copy()
[cc, ss, kd, ku, hk, pr, tw, wr, cl] = [pyautogui.countdown, time.sleep,
pyautogui.keyDown, pyautogui.keyUp, pyautogui.hotkey, pyautogui.press,,pyautogui.typewrite, pyautogui.write, pyautogui.click]
[gats, gaws, gwwt] = [pyautogui.getAllTitles, pyautogui.getAllWindows, pyautogui.getWindowsWithTitle]
[gawt, gaw] = [pyautogui.getActiveWindowTitle, pyautogui.getActiveWindow]
L = 4
qs, p2s, ps, = list(range(L)), list(range(L)), list(range(L))
text_temp, start = [''] * L, [0] * L
index_hks, index_hks2 = [hks] * L, [0] * L
index_latest_files = ['']
parent, w, ev, d, wd = [''] * L, [''] * L, [''] * L, [''] * (L + 1), [['']]*L
start_overall, outcome = '', ''
try: pycharm_win = [gaw()]
except: pass
path_chrome = "C:\Program Files\Google\Chrome\Application\chrome.exe"
path_core = os.path.join(os.path.expanduser("~"), 'PyCharmProjects', 'Parallel')
path_exec = os.path.join(path_core, "chromedriver.exe")
ext_details = [ ['ublock', 'cjpalhdlnbpafiamejdnhcphjbkeiagm'], ['keyboard_shortcuts', 'dkoadhojigekhckndaehenfbhcgfeepl'], ['browsec', 'omghfjlpggmjjaagoclmmobgdodcjboh'], ['itrace', 'njkmjblmcfiobddjgebnoeldkjcplfjb']]
ext_0= os.path.join(path_core, "Browsec")
ext_1 = os.path.join(path_core, "Keyboard")
ext_2 = os.path.join(path_core, "itrace")
ext_3 = os.path.join(path_core, "ublock")
if __name__ == '__main__':
ps =''
vars()
if len(ps) > 3:
ps_new = list(data_mygrouper(int(round(len(ps) / 2, ndigits=0)), ps))
for x in range(2): thread_all(ps_new[x], new_profile, workers=len(ps_new[x]) + 1, chunk=len(ps_new[x]) + 1), cc(5)
# new_profile
else: thread_all(ps, new_profile, workers=L + 1, chunk=L+1)
#thread_all(ps,new_profile)
tile_windows('v')
ext_update_method1(ps)
ext_remove(ps,'browsec')
ext_update_method2(ps)
关于python - 如何添加或删除 Chrome 扩展 "after"selenium 网络驱动程序已实例化/定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67946938/
我是 C 语言新手,我编写了这个 C 程序,让用户输入一年中的某一天,作为返回,程序将输出月份以及该月的哪一天。该程序运行良好,但我现在想简化该程序。我知道我需要一个循环,但我不知道如何去做。这是程序
我一直在努力找出我的代码有什么问题。这个想法是创建一个小的画图程序,并有红色、绿色、蓝色和清除按钮。我有我能想到的一切让它工作,但无法弄清楚代码有什么问题。程序打开,然后立即关闭。 import ja
我想安装screen,但是接下来我应该做什么? $ brew search screen imgur-screenshot screen
我有一个在服务器端工作的 UDP 套接字应用程序。为了测试服务器端,我编写了一个简单的 python 客户端程序,它发送消息“hello world how are you”。服务器随后应接收消息,将
我有一个 shell 脚本,它运行一个 Python 程序来预处理一些数据,然后运行一个 R 程序来执行一些长时间运行的任务。我正在学习使用 Docker 并且我一直在运行 FROM r-base:l
在 Linux 中。我有一个 c 程序,它读取一个 2048 字节的文本文件作为输入。我想从 Python 脚本启动 c 程序。我希望 Python 脚本将文本字符串作为参数传递给 c 程序,而不是将
对于一个类,我被要求编写一个 VHDL 程序,该程序接受两个整数输入 A 和 B,并用 A+B 替换 A,用 A-B 替换 B。我编写了以下程序和测试平台。它完成了实现和行为语法检查,但它不会模拟。尽
module Algorithm where import System.Random import Data.Maybe import Data.List type Atom = String ty
我想找到两个以上数字的最小公倍数 求给定N个数的最小公倍数的C++程序 最佳答案 int lcm(int a, int b) { return (a/gcd(a,b))*b; } 对于gcd,请查看
这个程序有错误。谁能解决这个问题? Error is :TempRecord already defines a member called 'this' with the same paramete
当我运行下面的程序时,我在 str1 和 str2 中得到了垃圾值。所以 #include #include #include using namespace std; int main() {
这是我的作业: 一对刚出生的兔子(一公一母)被放在田里。兔子在一个月大时可以交配,因此在第二个月的月底,每对兔子都会生出两对新兔子,然后死去。 注:在第0个月,有0对兔子。第 1 个月,有 1 对兔子
我编写了一个程序,通过对字母使用 switch 命令将十进制字符串转换为十六进制,但是如果我使用 char,该程序无法正常工作!没有 switch 我无法处理 9 以上的数字。我希望你能理解我,因为我
我是 C++ 新手(虽然我有一些 C 语言经验)和 MySQL,我正在尝试制作一个从 MySQL 读取数据库的程序,我一直在关注这个 tutorial但当我尝试“构建”解决方案时出现错误。 (我正在使
仍然是一个初学者,只是尝试使用 swift 中的一些基本函数。 有人能告诉我这段代码有什么问题吗? import UIKit var guessInt: Int var randomNum = arc
我正在用 C++11 编写一个函数,它采用 constant1 + constant2 形式的表达式并将它们折叠起来。 constant1 和 constant2 存储在 std::string 中,
我用 C++ 编写了这段代码,使用运算符重载对 2 个矩阵进行加法和乘法运算。当我执行代码时,它会在第 57 行和第 59 行产生错误,非法结构操作(两行都出现相同的错误)。请解释我的错误。提前致谢:
我是 C++ 的初学者,我想编写一个简单的程序来交换字符串中的两个字符。 例如;我们输入这个字符串:“EXAMPLE”,我们给它交换这两个字符:“E”和“A”,输出应该类似于“AXEMPLA”。 我在
我需要以下代码的帮助: 声明 3 个 double 类型变量,每个代表三角形的三个边中的一个。 提示用户为第一面输入一个值,然后 将用户的输入设置为您创建的代表三角形第一条边的变量。 将最后 2 个步
我是新来的,如果问题不好请见谅 任务:将给定矩阵旋转180度 输入: 1 4 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 输出: 16 15 14 13 12 11
我是一名优秀的程序员,十分优秀!