html页面结构 Shadow DOM in Selenium的详细解决办法
外网解决地址:
https://titusfortner.com/2021/11/22/shadow-dom-selenium.html
·当前为selenium版本3.x+chrome浏览器解决办法,selenium版本4.X参考外网地址内解决办法自寻查找
shadow_host = driver.find_element_by_css_selector('#mail-body')#进入shadow框架,类似iframe children = driver.execute_script('return arguments[0].shadowRoot.children', shadow_host) print(children) shadow_content = next(child for child in children if child.get_attribute('style') == 'color: #ff6600;font-size: 24.0px;"]') print(shadow_content.text)
#注意,定位方法都是css定位,xpath会报错
shadow_host = driver.find_element_by_css_selector('#mail-body')# shadow_root_dict = driver.execute_script('return arguments[0].shadowRoot', shadow_host) shadow_root_id = shadow_root_dict['shadow-6066-11e4-a52e-4f735466cecf'] shadow_root = WebElement(driver, shadow_root_id, w3c=True) shadow_content = shadow_root.find_element_by_css_selector('[style="color: #ff6600;font-size: 24.0px;"]') print(shadow_content.text)
·foxfire浏览器
shadow_host = driver.find_element_by_css_selector('#mail-body') children = driver.execute_script('return arguments[0].shadowRoot.children', shadow_host) #注意这里的遍历判断条件,child只有二级目录,不是所有子目录,以当前参考为例 child只有两个标签属性 div/style,所以判断条件只能写二级目录的条件 shadow_content = next(child for child in children if child.get_attribute('class') == 'selectable touch-callout break-word-links') #正则匹配出所有文本内需要的文本 result = re.findall("code (.*?) to verify", shadow_content.text)[0] print(result)