蓝色天空网 · mbsky.com
元素定位:By、唯一性和上下文
找到元素、找到正确元素、元素可操作是三件事。
固定本地测试页的实际浏览器结果,不是在线Python解释器。下载代码后可在独立环境修改输入并重新运行。
本章Python入口 · 完整实验实现 · 本站测试服务 · 本站页面交互

当前输入实际检查
| 实际检查 | 结果 |
|---|---|
| fixture-initial-no-severe-errors | 通过 |
| same-element-name | 通过 |
| same-element-class name | 通过 |
| same-element-css selector | 通过 |
| same-element-xpath | 通过 |
| tag-many | 通过 |
| link-text | 通过 |
| partial-link | 通过 |
| empty-list | 通过 |
| missing-single | 通过 |
| scoped-relative-xpath | 通过 |
| JS-returns-WebElement | 通过 |
| geometry-relative-input | 通过 |
| screenshot-saved-actual-browser | 通过 |
| PNG-magic-actual-browser | 通过 |
| PNG-extent-actual-browser | 通过 |
| all-created-sessions-quit | 通过 |
本章完整入口
from selenium_lab import *
@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')
if __name__ == "__main__":
run('selenium-element-positioning')