我正在尝试删除 div 内 iframe 内的弹出窗口。我必须找到关闭按钮并单击。我的代码能够找到 iframe 并在切换到 iframe 之前打印它并显示为空。它与包含弹出窗口的 iframe 相同。我在切换到它时遇到错误。
iframe:
<div id="sp_message_container_964490" style="display: block;">
<iframe src="https://cdn.privacy-mgmt.com/index.html
message_id=
964490&consentUUID=undefined&
preload_message=true&hasCsp=true&version=v1&
consent_origin=https%3A%2F%2Fcdn.privacy-
mgmt.com%2Fconsent%2Ftcfv2&mms_origin=https%3A%2F%2Fcdn.privacy-
mgmt.com%2Fmms%2Fv2&
consentLanguage=en" id="sp_message_iframe_964490" title="SP Consent Message">...
</iframe>
</div>
iframe 内:
<!DOCTYPE html><html lang="en"><head>
<title>Notice Message App</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-
scale=1.0,user-scalable=no,viewport-fit=cover">
...............
<button title="Essential cookies only" aria-label="Essential cookies only"
class="message-component message-button no-children focusable sp_choice_type_13"
style="opacity: 1; padding: 10px 20px; margin: 10px; border-width: 1px; border-color:
rgb(49, 87, 161); border-radius: 4px; border-style: solid; font-size: 14px; font-
weight: 700; color: rgb(255, 255, 255);
font-family: "trebuchet ms", helvetica, sans-serif; width: auto; background:
rgb(49, 87, 161);">Essential cookies only</button>
................
}</style></body></html>
我必须在 html 中访问此按钮。
我的代码:
divs = driver.find_elements(By.TAG_NAME, "div")
for div in divs:
if "message" in div.get_attribute("id"):
iframe = div.find_element(By.TAG_NAME, "iframe")
# for iframe in iframes:
try:
print("beofre switching to iframe", iframe.get_attribute("outerHTML"))
driver.switch_to.frame(iframe)
print("switched to iframe", iframe.get_attribute("outerHTML"))
content = driver.page_source
if 'consent' in content.lower():
handle_popups(driver)
return True
except Exception as e:
print(f"error switching to iframe {e}")
driver.switch_to.default_content()
return False
如何切换到iframe,为什么打印出来是空的?
我使用selenium webdriver等待iframe可用,并使用包含关键字的通用xpath切换到iframe,然后使用我定义的handle_popups函数单击关闭按钮。 我的新代码:
try:
iframe_path = "//iframe[contains(translate(@title,
'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'),
'consent')]"
WebDriverWait(driver,
5).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,
iframe_path)))
handle_popups(driver)
driver.switch_to.default_content()
return True
except Exception as e:
print(f"error finding iframes: {e}")
return False