蓝色天空网mbsky.com · 知识 · 实践 · 创造Selenium · 本地阅读预览
教程 / AI / 智能开发 / Selenium

浏览器上下文:弹窗、标签、frame与Cookie

每种上下文有自己的进入和退出方式。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

三类模态

Alert.text读取消息,accept关闭;confirm分别接受/取消产生true/false;prompt可send_keys后accept返回文本,dismiss产生null。不能对已关闭的同一个弹窗再accept/dismiss。

本站按钮或延迟JS触发模态,再wait alert_is_present,处理后断言页面记录结果。网页模态、HTML对话框和系统文件对话框不是同一种东西。

标签与frame

记录原handle,通过new_window或新集合差找到新标签,handles列表次序不保证代表打开时间。关闭新页后显式切回有效handle,quit清整会话。

iframe有独立文档上下文,switch_to.frame可用元素/索引/名称条件;default_content回顶层,parent_frame回上一层。frame不是window handle,不能混用。

Cookie和脚本

先导航到适用本站origin再add_cookie;domain/path/expiry/sameSite/secure/httpOnly各有条件。get_cookie与get_cookies、delete_cookie与delete_all_cookies分别检查。

HttpOnly Cookie可通过WebDriver接口管理但不可由页面document.cookie读取;本轮只用独立教学会话,不接触用户站点Cookie。执行JS返回值要有return;可记录对象、滚动位置或异步回调,但不自动等所有网络。

窗口和综合

尺寸、最大化、全屏、导航和刷新分别观察;headless命令成功不证明用户可见窗口。页面业务状态与窗口状态分开,退出后不继续调用已失效driver。

本站本地独立测试页的当前浏览器截图;本章具体操作、结果和环境见独立源码。

本站本地独立测试页的当前浏览器截图;本章具体操作、结果和环境见独立源码。
本站本地独立测试页的当前浏览器截图;本章具体操作、结果和环境见独立源码。

会话、窗口与文档上下文

条目/接口参数与条件返回/作用错误、范围与迁移
geturl导航到页面page_load_strategy与业务就绪分开
back/forward/refresh无额外URL历史/重载旧元素引用可能失效
title/current_url/page_source属性标题/URL/序列化页面不是同一种结果
close/quit当前上下文/整个会话关闭页/退出会话最后页与会话不可继续使用
set_window_size/rect尺寸/位置改变外框不恒等innerWidth/Height
maximize/minimize/fullscreen窗口命令窗口状态请求headless不证明可见桌面
switch_to.new_windowtab/window新上下文并切入记录handle,不猜列表顺序
window_handles/current_window_handle属性句柄列表/当前句柄顺序未保证
switch_to.window有效handle切换页关闭后原handle失效
switch_to.frameframe元素/索引/名称进入文档不是窗口句柄
parent_frame/default_content无参数上一层/顶层上下文层级不同
switch_to.alert当前模态Alert对象无模态会报错
Alert.accept/dismiss未关闭模态确认/取消不能对已关闭同一弹窗再处理
Alert.send_keysprompt文本设置输入alert/confirm不等同prompt
add_cookieget当前origin后cookie字典写对应Cookiedomain/path/expiry/sameSite条件
get_cookie/get_cookies名称/无参数字典/列表HttpOnly可WebDriver读,页面JS不可
delete_cookie/delete_all_cookies名称/无参数删除单个/全部仅本次独立会话
execute_script/execute_async_script本站JS/参数/回调序列化结果async需完成回调与script超时

模态可观察结果

条目/接口参数与条件返回/作用错误、范围与迁移
alert单消息accept后继续本站记录alert已确认
confirm接受/取消true/false两次重新触发,不复用已关Alert
prompt输入接受/取消文本/null空串与取消null不同
Cookie expiry整数秒Unix时间过期时刻不是毫秒
SameSiteStrict/Lax/None跨站发送条件None通常另需Secure
HttpOnlybool页面JS不读WebDriver接口可管理

本章独立核心源码与验证步骤

python · 阅读源码
from selenium_lab import *

@case('selenium-browser-operator')
def contexts(l,d,b,s):
 click(d,'alert-btn');alert=wait(d).until(EC.alert_is_present());l.eq('alert-text',alert.text,'蓝色天空网提示');alert.accept();l.eq('alert-after-accept',d.find_element(By.ID,'modal-result').text,'alert已确认')
 for accepted in[True,False]:click(d,'confirm-btn');a=wait(d).until(EC.alert_is_present());a.accept()if accepted else a.dismiss();l.eq('confirm-'+str(accepted),d.find_element(By.ID,'modal-result').text,str(accepted).lower())
 click(d,'prompt-btn');a=wait(d).until(EC.alert_is_present());a.send_keys('mbsky.com');a.accept();l.eq('prompt-value',d.find_element(By.ID,'modal-result').text,'mbsky.com');click(d,'prompt-btn');wait(d).until(EC.alert_is_present()).dismiss();l.eq('prompt-dismiss-null',d.find_element(By.ID,'modal-result').text,'null');origin=d.current_window_handle;before=set(d.window_handles);click(d,'new-tab');wait(d).until(EC.number_of_windows_to_be(2));new=(set(d.window_handles)-before).pop();d.switch_to.window(new);l.check('newtab-title','学习计划'in d.title);d.close();d.switch_to.window(origin);d.switch_to.frame(d.find_element(By.ID,'frame'));l.eq('frame-text',d.find_element(By.ID,'inside').text,'第一层frame');d.switch_to.frame(d.find_element(By.ID,'inner-frame'));l.eq('nested-frame',d.find_element(By.ID,'nested').text,'第二层frame');d.switch_to.parent_frame();l.eq('parent-frame',d.find_element(By.ID,'inside').text,'第一层frame');d.switch_to.default_content();d.add_cookie({'name':'mbsky_test','value':'learning','path':'/','sameSite':'Lax'});l.eq('get-cookie',d.get_cookie('mbsky_test')['value'],'learning');d.add_cookie({'name':'mbsky_http_only','value':'own','path':'/','httpOnly':True});l.check('HTTPOnly-not-JS-readable','mbsky_http_only'not in d.execute_script('return document.cookie'));l.check('HTTPOnly-WebDriver-readable',d.get_cookie('mbsky_http_only')['httpOnly']);d.delete_cookie('mbsky_test');l.eq('deleted-single',d.get_cookie('mbsky_test'),None);d.delete_all_cookies();l.eq('deleted-all',d.get_cookies(),[]);l.eq('JS-return-title',d.execute_script('return document.title'),d.title)

if __name__ == "__main__":
    run('selenium-browser-operator')
浏览器上下文:弹窗、标签、frame与Cookie:独立本地浏览器实验

所需环境:Windows/Python3.12/Selenium4.52.0/Edge及驱动156.0.4314.58;GridServer4.52/Temurin21.0.13;独立无头会话

当前源码 SHA256:f8134632e265b50016622eba95f3c72a8c204061b99f79ebd8863541dbd1ceb6

预期结果 · 待实际运行核验
  • 本章固定输入断言通过,错误/等待/业务结果和退出分别验证
  • 截图对应本站当前测试页;未执行平台或能力不因本轮通过自动升级

完整共享实现:仅本章实际调用的分支已验

python · 阅读源码
import os,sys,json,time,hashlib,secrets,warnings,argparse,struct,io,zipfile,inspect,contextlib,socket,threading,subprocess,urllib.request
from pathlib import Path
from contextlib import contextmanager
from concurrent.futures import ThreadPoolExecutor
import selenium
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.edge.service import Service
from selenium.webdriver.edge.options import Options
from selenium.webdriver.support.ui import WebDriverWait,Select
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import NoSuchElementException,TimeoutException,StaleElementReferenceException,ElementClickInterceptedException,InvalidArgumentException,NoSuchWindowException,InvalidSessionIdException,UnexpectedTagNameException
from selenium.webdriver.support.relative_locator import locate_with
from fixture_site import site,download_bytes
CASES={}
def case(key):
 def decorate(f):CASES[key]=f;return f
 return decorate
class Lab:
 def __init__(self,out):self.out=out;self.checks=[];self.figures=[];self.pending=[];self.metadata={};self.session_opened=[];self.session_closed=[]
 def check(self,name,condition,actual=None):self.checks.append(dict(case=name,passed=bool(condition),actual=actual));assert condition,(name,actual)
 def eq(self,name,a,b):self.check(name,a==b,dict(actual=a,expected=b))
 def err(self,name,typ,fn):
  try:fn()
  except typ as error:self.check(name,True,dict(type=type(error).__name__,message=str(error).splitlines()[0]));return error
  raise AssertionError('Expected error missing '+name)
 def pending_case(self,name,reason):self.pending.append(dict(name=name,status='pending',reason=reason))
 def capture(self,d,name='actual-browser'):
  p=self.out/(name+'.png');self.check('screenshot-saved-'+name,d.save_screenshot(str(p)));data=p.read_bytes();self.check('PNG-magic-'+name,data.startswith(b'\x89PNG\r\n\x1a\n'));width,height=struct.unpack('>II',data[16:24]);self.check('PNG-extent-'+name,width>100 and height>100,dict(width=width,height=height));self.figures.append(dict(file=p.name,sha256=hashlib.sha256(data).hexdigest(),width=width,height=height))
def options_for(lab,name='browser',preferences=None,extra_arguments=None):
 opts=Options();opts.binary_location=os.environ.get('MBSKY_EDGE_BINARY',r'C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe');profile=lab.out/'profiles'/(name+'-'+secrets.token_hex(3));opts.add_argument('--headless=new');opts.add_argument('--no-first-run');opts.add_argument('--disable-background-networking');opts.add_argument('--disable-extensions');opts.add_argument('--window-size=1400,1000');opts.add_argument('--user-data-dir='+str(profile));prefs={'download.default_directory':str(lab.out/'downloads'),'download.prompt_for_download':False,'download.directory_upgrade':True,'safebrowsing.enabled':True,'session.restore_on_startup':4,'session.startup_urls':['about:blank'],'homepage':'about:blank','homepage_is_newtabpage':False};prefs.update(preferences or{});opts.add_experimental_option('prefs',prefs);
 for arg in extra_arguments or[]:opts.add_argument(arg)
 return opts
@contextmanager
def browser(lab,name='browser',preferences=None,remote=None,extra_arguments=None):
 (lab.out/'downloads').mkdir(exist_ok=True);opts=options_for(lab,name,preferences,extra_arguments);driver=None;service=None
 try:
  if remote:
   opts.enable_downloads=True;driver=webdriver.Remote(command_executor=remote,options=opts)
  else:
   executable=os.environ['MBSKY_EDGE_DRIVER'];service=Service(executable_path=executable,log_output=str(lab.out/(name+'-webdriver.log')),popen_kw={'creation_flags':getattr(subprocess,'CREATE_NO_WINDOW',0)});driver=webdriver.Edge(service=service,options=opts)
  lab.session_opened.append(driver.session_id);driver.implicitly_wait(0);driver.set_page_load_timeout(10);driver.set_script_timeout(5);driver.get('about:blank');yield driver
 finally:
  if driver is not None:
   session=driver.session_id;driver.quit();lab.session_closed.append(session)
  if service is not None:service.stop()
def wait(d,timeout=4):return WebDriverWait(d,timeout,poll_frequency=.05)
def click(d,id):d.find_element(By.ID,id).click()
def search(d,query):
 box=d.find_element(By.ID,'query');box.clear();box.send_keys(query,Keys.ENTER);wait(d).until(lambda x:x.find_element(By.ID,'results').get_attribute('data-status')=='done');return [e.text for e in d.find_elements(By.CSS_SELECTOR,'#result-list li')]
def run(key):
 ap=argparse.ArgumentParser();ap.add_argument('--output',type=Path,default=Path('generated'));args=ap.parse_args();out=(args.output/('mbsky-selenium-'+secrets.token_hex(5))).resolve();out.mkdir(parents=True);lab=Lab(out)
 with warnings.catch_warnings(record=True)as found:
  warnings.simplefilter('always')
  with site()as(base,state):
   with browser(lab)as d:
    lab.metadata['browser_initialization_logs']=d.get_log('browser');d.get(base);initial=d.get_log('browser');lab.metadata['fixture_initial_logs']=initial;lab.check('fixture-initial-no-severe-errors',not any(v.get('level')=='SEVERE'and v.get('message','').startswith(base)for v in initial),initial);lab.metadata['capabilities']={k:d.capabilities.get(k)for k in['browserName','browserVersion','platformName','msedge']};
    try:CASES[key](lab,d,base,state)
    except BaseException:
     try:lab.capture(d,'failure')
     except Exception as capture_error:lab.metadata['failure_capture_error']=str(capture_error)
     (out/'failure-observations.json').write_text(json.dumps(dict(checks=lab.checks,metadata=lab.metadata,figures=lab.figures),ensure_ascii=False,indent=2),encoding='utf8');raise
    d.switch_to.default_content();lab.capture(d)
   lab.eq('all-created-sessions-quit',sorted(lab.session_opened),sorted(lab.session_closed))
 payload=dict(chapter=key,passed=True,selenium_version=selenium.__version__,checks=lab.checks,figures=lab.figures,pending=lab.pending,warnings=[dict(category=w.category.__name__,message=str(w.message))for w in found],metadata=lab.metadata,source_scripts_executed=False,own_output=out.name,scope='Only named actual local fixture/browser cases; all source semantics/platforms separate');(out/'observations.json').write_text(json.dumps(payload,ensure_ascii=False,indent=2),encoding='utf8');print(json.dumps(payload,ensure_ascii=False))
@case('selenium-tutorial')
def tutorial(l,d,b,s):
 l.eq('initial-title',d.title,'蓝色天空网自动化实验');l.eq('enter-submit-search',search(d,'CSS'),['CSS布局','CSS选择器']);l.eq('search-visible-count',d.find_element(By.ID,'result-status').text,'找到 2 条教程');l.check('brand-visible','mbsky.com'in d.find_element(By.TAG_NAME,'header').text)
@case('selenium-intro')
def intro(l,d,b,s):
 l.eq('current-browser',d.capabilities['browserName'],'MicrosoftEdge');l.eq('current-browser-version',d.capabilities['browserVersion'],'156.0.4314.58');l.eq('current-binding',selenium.__version__,'4.52.0');l.check('real-WebDriver-session',bool(d.session_id));l.eq('not-legacy-name-method',hasattr(d,'find_element_by_id'),False);l.pending_case('IDE-and-other-browsers','Actual IDE desktop/recording, Firefox/Safari/IE/mobile contexts not executed')
@case('selenium-install')
def install(l,d,b,s):
 l.eq('binding-version',selenium.__version__,'4.52.0');l.check('current-Service-argument','service'in inspect.signature(webdriver.Edge).parameters);l.check('old-executable_path-driverarg-absent','executable_path'not in inspect.signature(webdriver.Edge).parameters);l.check('actual-title',bool(d.title));l.eq('actual-driver-match',d.capabilities['msedge']['msedgedriverVersion'].split()[0],'156.0.4314.58');l.pending_case('Selenium-Manager-and-load-stop','Explicit signed localdriver used; automaticManager downloads and slownetwork/page_load_strategy/window.stop combinations not all executed')
@case('selenium-webdriver')
def lifecycle(l,d,b,s):
 original=d.current_window_handle;d.set_window_size(1100,800);rect=d.get_window_rect();l.eq('requested-outer-size',(rect['width'],rect['height']),(1100,800));d.get(b+'/other');l.check('other-title','学习计划'in d.title);d.back();l.eq('back-path',d.current_url,b+'/');d.forward();l.eq('forward-path',d.current_url,b+'/other');d.execute_script('window.transient=77');d.refresh();l.eq('refresh-rebuilds-document',d.execute_script('return window.transient??null'),None);d.maximize_window();l.check('maximize-positive',d.get_window_rect()['width']>0);d.minimize_window();l.check('minimize-command',True);d.fullscreen_window();l.check('fullscreen-positive',d.get_window_rect()['height']>0);d.set_window_size(1400,1000);d.switch_to.new_window('tab');new=d.current_window_handle;l.check('new-distinct-handle',new!=original);d.get(b+'/other');d.close();d.switch_to.window(original);l.eq('close-only-current-tab',len(d.window_handles),1);d.get(b);l.pending_case('actual-visible-window','Window commands executed headless; visible OS maximize/minimize/fullscreen not accepted')
@case('selenium-element-positioning')
def locating(l,d,b,s):
 expected=d.find_element(By.ID,'query');locators=[(By.NAME,'q'),(By.CLASS_NAME,'search-field'),(By.CSS_SELECTOR,'input.search-field.stable-field'),(By.XPATH,"//input[@data-testid='query']")]
 for how,value in locators:l.eq('same-element-'+how,d.find_element(how,value).id,expected.id)
 l.check('tag-many',len(d.find_elements(By.TAG_NAME,'input'))>=8);l.eq('link-text',d.find_element(By.LINK_TEXT,'查看学习计划').get_attribute('id'),'learn-link');l.eq('partial-link',d.find_element(By.PARTIAL_LINK_TEXT,'学习计划').get_attribute('id'),'learn-link');l.eq('empty-list',d.find_elements(By.ID,'not-present'),[]);l.err('missing-single',NoSuchElementException,lambda:d.find_element(By.ID,'not-present'));l.eq('scoped-relative-xpath',d.find_element(By.ID,'search-form').find_element(By.XPATH,'.//input').id,expected.id);l.eq('JS-returns-WebElement',d.execute_script("return document.querySelector('#query')").id,expected.id);relative=d.find_element(locate_with(By.TAG_NAME,'input').to_left_of(d.find_element(By.ID,'search-submit')));l.eq('geometry-relative-input',relative.id,expected.id);l.pending_case('ShadowRoot-and-compound-class','Open/closed shadow roots and all invalid compound CLASS_NAME cases not executed')
@case('selenium-ele-operator')
def elements(l,d,b,s):
 el=d.find_element(By.ID,'username');el.send_keys('old');el.clear();el.send_keys('mbsky');l.eq('clear-and-send',el.get_property('value'),'mbsky');a=d.find_element(By.ID,'attribute');a.clear();a.send_keys('changed');l.eq('attribute-property-fallback',a.get_attribute('value'),'changed');l.eq('DOM-original-attribute',a.get_dom_attribute('value'),'initial');l.eq('visible-text-only',d.find_element(By.ID,'visible-text').text,'看得见的正文');click(d,'subscribe');l.check('checkbox-selected',d.find_element(By.ID,'subscribe').is_selected());click(d,'subscribe');l.check('checkbox-unselected',not d.find_element(By.ID,'subscribe').is_selected());click(d,'mobile');l.check('radio-exclusive',d.find_element(By.ID,'mobile').is_selected()and not d.find_element(By.ID,'web').is_selected());click(d,'mobile');l.check('radio-repeat-stays-selected',d.find_element(By.ID,'mobile').is_selected());select=Select(d.find_element(By.ID,'topic'));select.select_by_visible_text('CSS');l.eq('select-text',select.first_selected_option.get_attribute('value'),'css');select.select_by_value('js');l.eq('select-value',select.first_selected_option.text,'JavaScript');select.select_by_index(0);l.eq('select-index',select.first_selected_option.text,'HTML5');multi=Select(d.find_element(By.ID,'topics'));multi.select_by_value('html');multi.select_by_value('css');l.eq('multi-selected',len(multi.all_selected_options),2);multi.deselect_all();l.eq('multi-deselected',multi.all_selected_options,[]);l.err('Select-needs-native-tag',UnexpectedTagNameException,lambda:Select(d.find_element(By.ID,'results')));click(d,'button');l.eq('real-button-click',d.find_element(By.ID,'clicked').text,'1')
@case('selenium-wait')
def waiting(l,d,b,s):
 hidden=wait(d).until(EC.presence_of_element_located((By.ID,'hidden')));l.check('presence-not-visible',not hidden.is_displayed());l.check('visibility-condition-false',not EC.visibility_of_element_located((By.ID,'hidden'))(d));click(d,'start-delay');d.implicitly_wait(2);start=time.monotonic();late=d.find_element(By.ID,'late');l.eq('implicit-finds-late',late.text,'异步元素已出现');l.check('implicit-until-not-always2sec',time.monotonic()-start<2.5);d.implicitly_wait(0);wait(d).until(EC.visibility_of_element_located((By.ID,'hidden')));l.check('visible-after-update',hidden.is_displayed());button=wait(d).until(EC.element_to_be_clickable((By.ID,'disabled')));l.check('enabled-after-update',button.is_enabled());l.err('explicit-timeout',TimeoutException,lambda:wait(d,.25).until(EC.presence_of_element_located((By.ID,'never'))));l.eq('find-elements-missing-list',d.find_elements(By.ID,'never'),[]);old=d.find_element(By.ID,'replace-target');click(d,'replace');l.check('stale-observed',wait(d).until(EC.staleness_of(old)));l.eq('relocated-new-text',d.find_element(By.ID,'replace-target').text,'替换后的新节点');d.find_element(By.ID,'covered').location_once_scrolled_into_view;l.check('EC-clickable-doesnot-check-overlay',bool(EC.element_to_be_clickable((By.ID,'covered'))(d)));l.err('actual-overlay-intercept',ElementClickInterceptedException,lambda:click(d,'covered'))
@case('selenium-browser-operator')
def contexts(l,d,b,s):
 click(d,'alert-btn');alert=wait(d).until(EC.alert_is_present());l.eq('alert-text',alert.text,'蓝色天空网提示');alert.accept();l.eq('alert-after-accept',d.find_element(By.ID,'modal-result').text,'alert已确认')
 for accepted in[True,False]:click(d,'confirm-btn');a=wait(d).until(EC.alert_is_present());a.accept()if accepted else a.dismiss();l.eq('confirm-'+str(accepted),d.find_element(By.ID,'modal-result').text,str(accepted).lower())
 click(d,'prompt-btn');a=wait(d).until(EC.alert_is_present());a.send_keys('mbsky.com');a.accept();l.eq('prompt-value',d.find_element(By.ID,'modal-result').text,'mbsky.com');click(d,'prompt-btn');wait(d).until(EC.alert_is_present()).dismiss();l.eq('prompt-dismiss-null',d.find_element(By.ID,'modal-result').text,'null');origin=d.current_window_handle;before=set(d.window_handles);click(d,'new-tab');wait(d).until(EC.number_of_windows_to_be(2));new=(set(d.window_handles)-before).pop();d.switch_to.window(new);l.check('newtab-title','学习计划'in d.title);d.close();d.switch_to.window(origin);d.switch_to.frame(d.find_element(By.ID,'frame'));l.eq('frame-text',d.find_element(By.ID,'inside').text,'第一层frame');d.switch_to.frame(d.find_element(By.ID,'inner-frame'));l.eq('nested-frame',d.find_element(By.ID,'nested').text,'第二层frame');d.switch_to.parent_frame();l.eq('parent-frame',d.find_element(By.ID,'inside').text,'第一层frame');d.switch_to.default_content();d.add_cookie({'name':'mbsky_test','value':'learning','path':'/','sameSite':'Lax'});l.eq('get-cookie',d.get_cookie('mbsky_test')['value'],'learning');d.add_cookie({'name':'mbsky_http_only','value':'own','path':'/','httpOnly':True});l.check('HTTPOnly-not-JS-readable','mbsky_http_only'not in d.execute_script('return document.cookie'));l.check('HTTPOnly-WebDriver-readable',d.get_cookie('mbsky_http_only')['httpOnly']);d.delete_cookie('mbsky_test');l.eq('deleted-single',d.get_cookie('mbsky_test'),None);d.delete_all_cookies();l.eq('deleted-all',d.get_cookies(),[]);l.eq('JS-return-title',d.execute_script('return document.title'),d.title)
@case('selenium-mouse-and-keyboard-operation')
def actions(l,d,b,s):
 ActionChains(d).click(d.find_element(By.ID,'button')).perform();l.eq('pointer-click-count',d.find_element(By.ID,'clicked').text,'1');ActionChains(d).double_click(d.find_element(By.ID,'double')).perform();l.eq('double-event',d.find_element(By.ID,'doubled').text,'1');ActionChains(d).context_click(d.find_element(By.ID,'context')).perform();l.eq('right-event',d.find_element(By.ID,'context-count').text,'1');ActionChains(d).move_to_element(d.find_element(By.ID,'hoverbox')).perform();l.check('hover-tip-visible',d.find_element(By.ID,'hover-tip').is_displayed());source=d.find_element(By.ID,'dragger');target=d.find_element(By.ID,'dropzone');ActionChains(d).drag_and_drop(source,target).perform();l.eq('actual-pointer-drop',d.find_element(By.ID,'drag-result').text,'已移到目标区域');l.eq('down-up-events',d.find_element(By.ID,'drag-events').text,'down up');box=d.find_element(By.ID,'keyboard');box.send_keys('old text');ActionChains(d).click(box).key_down(Keys.CONTROL).send_keys('a').key_up(Keys.CONTROL).send_keys('mbsky.com').perform();l.eq('select-and-replace',box.get_property('value'),'mbsky.com');box.clear();ActionChains(d).click(box).key_down(Keys.SHIFT).send_keys('a').key_up(Keys.SHIFT).perform();l.eq('shift-upper',box.get_property('value'),'A');box.send_keys(Keys.TAB);l.eq('tab-focus',d.switch_to.active_element.get_attribute('id'),'next-focus');ActionChains(d).reset_actions();l.pending_case('native-clipboard-and-HTML5-DataTransfer','No user clipboard access; actual pointer drag fixture tested, arbitrary native/HTML5DataTransfer widgets not accepted')
@case('selenium-file-operator')
def files(l,d,b,s):
 p=l.out/'mbsky-upload.txt';body='蓝色天空网 · mbsky.com\nSelenium真实字节上传\n'.encode();p.write_bytes(body);el=d.find_element(By.ID,'upload');el.send_keys(str(p));l.eq('DOM-files-name',d.execute_script('return arguments[0].files[0].name',el),p.name);l.eq('DOM-files-size',d.execute_script('return arguments[0].files[0].size',el),len(body));click(d,'upload-send');wait(d).until(lambda x:x.find_element(By.ID,'upload-result').get_attribute('data-status')=='done');actual=json.loads(d.find_element(By.ID,'upload-result').text);l.eq('server-received-sha',actual['sha256'],hashlib.sha256(body).hexdigest());l.eq('server-received-length',actual['bytes'],len(body));l.eq('server-independent-record',s['uploads'][-1],actual);l.err('missing-file-not-selected',InvalidArgumentException,lambda:el.send_keys(str(l.out/'no-such-file.txt')));target=l.out/'downloads/mbsky-example.zip';l.check('fresh-download-not-existing',not target.exists());click(d,'download');wait(d,8).until(lambda _:target.is_file()and not list(target.parent.glob('*.crdownload'))and target.read_bytes()==download_bytes());l.eq('download-actual-bytes',hashlib.sha256(target.read_bytes()).hexdigest(),hashlib.sha256(download_bytes()).hexdigest())
 with zipfile.ZipFile(target)as z:l.eq('ZIP-CRC',z.testzip(),None);l.eq('ZIP-exact-members',z.namelist(),['README.txt','example.html']);l.check('ZIP-brand','mbsky.com'in z.read('example.html').decode())
 l.pending_case('Grid-managed-download-and-native-dialog','Only local Edge native input and actual ZIP download tested; Actual same-host Grid managed downloads separately tested in Grid chapter; cross-machine LocalFileDetector/AutoIT/native picker not executed')
@case('selenium-grid')
def grid_case(l,d,b,s):
 from grid_runtime import grid,local_json
 with grid(l.out)as(remote,status):
  l.eq('actual-single-node',len(status['value']['nodes']),1);l.eq('node-two-slots',len(status['value']['nodes'][0]['slots']),2);barrier=threading.Barrier(3)
  def worker(index):
   with browser(l,name='grid-'+str(index),remote=remote)as rd:
    rd.get(b+'/search');session=rd.session_id;barrier.wait(timeout=30);barrier.wait(timeout=30);rows=search(rd,'CSS');rd.get(b);click(rd,'download');wait(rd,8).until(lambda _:'mbsky-example.zip'in rd.get_downloadable_files());local=l.out/'remote-downloads'/str(index);rd.download_file('mbsky-example.zip',str(local));l.eq('managed-download-bytes-'+str(index),hashlib.sha256((local/'mbsky-example.zip').read_bytes()).hexdigest(),hashlib.sha256(download_bytes()).hexdigest());rd.delete_downloadable_files();l.eq('managed-download-deleted-'+str(index),rd.get_downloadable_files(),[]);return {'session':session,'rows':rows,'version':rd.capabilities['browserVersion']}
  with ThreadPoolExecutor(max_workers=2)as pool:
   futures=[pool.submit(worker,i)for i in range(2)]
   try:
    barrier.wait(timeout=30);active=local_json(remote+'/status');occupied=[slot['session']for node in active['value']['nodes']for slot in node['slots']if slot['session']is not None];l.eq('real-concurrent-slots',len(occupied),2);l.metadata['grid_active_slots']=occupied;barrier.wait(timeout=30);results=[f.result(timeout=30)for f in futures]
   except BaseException:barrier.abort();raise
  l.eq('two-distinct-sessions',len({v['session']for v in results}),2)
  for v in results:l.eq('remote-search-result',v['rows'],['CSS布局','CSS选择器']);l.eq('remote-browser-version',v['version'],'156.0.4314.58')
  l.metadata['grid_results']=results;wait(d,4).until(lambda _:all(slot['session']is None for node in local_json(remote+'/status')['value']['nodes']for slot in node['slots']))
 l.pending_case('distributed-other-platforms','Actual local Standalone/2concurrent remote Edge sessions; separate Hub+Node machines, Docker/Kubernetes, other OS/browser and node-failure recovery not executed')
@case('selenium-unittest')
def framework_case(l,d,b,s):
 import xml.etree.ElementTree as ET
 root=Path(__file__).resolve().parent;output=l.out/'framework';output.mkdir();env=os.environ.copy();env.update(MBSKY_TEST_OUTPUT=str(output),PYTHONDONTWRITEBYTECODE='1');unit=subprocess.run([sys.executable,'-E','-s','-B','-X','utf8','-m','unittest','-v','test_unittest_flow.py'],cwd=root,env=env,capture_output=True,text=True,encoding='utf8',timeout=50,creationflags=getattr(subprocess,'CREATE_NO_WINDOW',0));(output/'unittest.txt').write_text(unit.stdout+unit.stderr,encoding='utf8');l.eq('unittest-exit',unit.returncode,0);l.check('unittest-2actual-tests','Ran 2 tests'in unit.stderr and'OK'in unit.stderr);config=output/'pytest.ini';config.write_text('[pytest]\n',encoding='utf8');report=output/'report.html';junit=output/'pytest.xml';test=subprocess.run([sys.executable,'-E','-s','-B','-X','utf8','-m','pytest',str(root/'test_pytest_flow.py'),'-q','-n','2','-p','no:cacheprovider','-c',str(config),'--basetemp',str(output/'pytest-temp'),'--html',str(report),'--self-contained-html','--junitxml',str(junit)],cwd=output,env=env,capture_output=True,text=True,encoding='utf8',timeout=70,creationflags=getattr(subprocess,'CREATE_NO_WINDOW',0));(output/'pytest.txt').write_text(test.stdout+test.stderr,encoding='utf8');l.eq('pytest-exit',test.returncode,0);suites=ET.parse(junit).getroot().findall('testsuite');l.eq('pytest-actual-count',sum(int(v.attrib['tests'])for v in suites),2);l.eq('pytest-no-fail-errors',sum(int(v.attrib.get('failures','0'))+int(v.attrib.get('errors','0'))for v in suites),0);l.check('HTML-real-report',report.is_file()and report.stat().st_size>1000);receipts=list(output.glob('*/cleanup.json'));l.eq('four-independent-test-cleanups',len(receipts),4)
 for receipt in receipts:
  value=json.loads(receipt.read_text(encoding='utf8'));l.eq('fixture-sessions-closed-'+receipt.parent.name,value['opened'],value['closed']);l.eq('one-browser-per-test-'+receipt.parent.name,len(value['opened']),1)
 l.metadata['framework']={'unittest_tests':2,'pytest_tests':2,'pytest_workers':2,'warnings_and_full_report':'retained in current private output, not publicly exported'};l.eq('framework-search-outcome',search(d,'JavaScript'),['JavaScript事件']);l.pending_case('framework-failure-init-and-CI','Actual two unittest and two pytest/xdist successes plus cleanup receipts; intentional failed setup/retry/CI runners/other language frameworks not executed')
@case('selenium-advanced')
def advanced(l,d,b,s):
 from grid_runtime import local_proxy
 l.eq('no-jQuery-assumption',d.execute_script('return typeof window.jQuery'),'undefined');click(d,'trigger-fetch');wait(d).until(lambda x:x.find_element(By.ID,'fetch-result').get_attribute('data-ready')=='true');l.eq('actual-fetch-result',d.find_element(By.ID,'fetch-result').text,'2');token=d.find_element(By.ID,'token');token.send_keys('wrong');click(d,'test-token');l.eq('test-token-negative',d.find_element(By.ID,'token-result').text,'测试校验失败');token.clear();token.send_keys('MBSKY-TEST');click(d,'test-token');l.eq('test-token-positive',d.find_element(By.ID,'token-result').text,'测试校验通过')
 with local_proxy(b)as(proxy,forwarded):
  with browser(l,'local-proxy',extra_arguments=['--proxy-server='+proxy,'--proxy-bypass-list=<-loopback>'])as pd:
   pd.get(b+'/search');l.eq('proxy-actual-search',search(pd,'CSS'),['CSS布局','CSS选择器']);l.check('actual-proxy-forwarded-request',any('/api/search?'in u for u in forwarded),forwarded)
 before=sum(v['path']=='/pixel.png'for v in s['requests'])
 with browser(l,'images-off',preferences={'profile.managed_default_content_settings.images':2})as off:
  off.get(b);l.eq('image-disabled-natural-width',off.execute_script("return document.querySelector('#probe-image').naturalWidth"),0);l.eq('disabled-image-request-count',sum(v['path']=='/pixel.png'for v in s['requests']),before);l.check('JS-still-executes',off.execute_script('return window.fixtureBoot===true'))
 with browser(l,'javascript-off',preferences={'profile.managed_default_content_settings.javascript':2})as off:
  off.get(b);l.eq('page-JS-disabled-marker',off.execute_script('return window.fixtureBoot??null'),None);l.check('static-HTML-still-present',bool(off.find_elements(By.ID,'query')))
 l.pending_case('production-captcha-and-external-proxy','Only controlled local test-token/localproxy, resource prefs and ownfetch executed; no production CAPTCHA solving service, external IP-evasion or dynamic live proxy switching')
@case('selenium-headless')
def headless(l,d,b,s):
 l.check('headless-user-agent','Headless' in d.execute_script('return navigator.userAgent'));viewport=d.execute_script('return {width:innerWidth,height:innerHeight,dpr:devicePixelRatio,mode:document.compatMode}');l.eq('standards-mode',viewport['mode'],'CSS1Compat');l.check('actual-viewport-positive',viewport['width']>500 and viewport['height']>300,viewport);l.check('real-page-JS',d.execute_script('return window.fixtureBoot===true'));l.check('actual-image-decoded',d.execute_script("return document.querySelector('#probe-image').complete&&document.querySelector('#probe-image').naturalWidth===1"));d.execute_script("console.error('MBSKY expected browser log')");logs=d.get_log('browser');l.check('actual-browser-log',any('MBSKY expected browser log'in v['message']for v in logs));l.check('only-planned-fixture-console-error',not any(v.get('level')=='SEVERE'and'MBSKY expected browser log'not in v.get('message','')for v in logs),logs);l.metadata['browser_logs']=logs;l.metadata['viewport']=viewport;l.eq('headless-search',search(d,'HTML5'),['HTML5语义化']);l.pending_case('headful-and-other-headless-platforms','Actual Edge headless screenshot/viewport/JS/log; headful visible GUI/Chrome/Firefox/Safari and comparative performance not executed')
@case('selenium-practical')
def practical(l,d,b,s):
 def fill(values):
  for id,value in values.items():el=d.find_element(By.ID,id);el.clear();el.send_keys(value)
 def status():return d.find_element(By.ID,'auth-result').get_attribute('data-status')
 d.get(b+'/register');fill({'username':'mbsky_learner','password':'local-learning-only','email':'learner@example.test','confirm-password':'different'});click(d,'register-button');wait(d).until(lambda _:status()=='error');l.eq('register-mismatch',d.find_element(By.ID,'auth-result').text,'两次密码不一致');fill({'confirm-password':'local-learning-only'});click(d,'register-button');wait(d).until(lambda _:status()=='success');l.eq('register-positive',d.find_element(By.ID,'auth-result').text,'注册成功');click(d,'register-button');wait(d).until(lambda _:status()=='error');l.eq('duplicate-user',d.find_element(By.ID,'auth-result').text,'用户已存在');l.eq('one-real-fixture-user',list(s['users']),['mbsky_learner']);d.get(b+'/login');fill({'username':'mbsky_learner','password':'wrong'});click(d,'login-button');wait(d).until(lambda _:status()=='error');l.eq('login-wrong-password',d.find_element(By.ID,'auth-result').text,'用户名或密码错误');fill({'password':'local-learning-only'});click(d,'login-button');wait(d).until(lambda _:status()=='success');l.eq('current-user-visible',d.find_element(By.ID,'current-user').text,'mbsky_learner');l.check('actual-session-cookie',d.get_cookie('mbsky_test_session')['httpOnly']);click(d,'logout');wait(d).until(lambda _:status()=='loggedout');l.eq('logout-clears-current-user',d.find_element(By.ID,'current-user').text,'');l.eq('logout-cookie-removed',d.get_cookie('mbsky_test_session'),None);l.eq('server-session-removed',s['cookies'],{});d.get(b+'/search');l.eq('practical-Enter-search',search(d,'CSS'),['CSS布局','CSS选择器']);box=d.find_element(By.ID,'query');box.clear();box.send_keys('not-present');click(d,'search-submit');wait(d).until(lambda x:x.find_element(By.ID,'results').get_attribute('data-status')=='done');l.eq('empty-search-visible',d.find_element(By.ID,'result-status').text,'没有匹配结果');l.pending_case('production-registration','Only isolated in-memory fictional test users; production membership, email/SMS, billing, security/performance acceptance not covered')
完整共享实现:仅本章实际调用的分支已验

所需环境:Windows/Python3.12/Selenium4.52.0/Edge及驱动156.0.4314.58;GridServer4.52/Temurin21.0.13;独立无头会话

当前源码 SHA256:c3cdd141191834896fa1cab00fac02be66f4736a9d72d123175ebc8c27916e93

下载本站示例源码
预期结果 · 待实际运行核验
  • 本章固定输入断言通过,错误/等待/业务结果和退出分别验证
  • 截图对应本站当前测试页;未执行平台或能力不因本轮通过自动升级

常见错误与边界

  • 混淆存在、可见、启用、未遮挡及业务完成;沿用已移除定位/构造API。
  • 只看命令返回或文件名,忽略服务器字节、实际结果与会话清理。

练习与解答

在本站独立fixture改变一个延迟、元素状态或输入,先预测成功/拒绝/超时再运行。

展开参考解答

按真实可见状态、事件、HTTP响应、字节和清理记录判定,不能把更多等待或无异常退出当业务正确。

规范与官方依据