【发布时间】:2019-08-23 19:00:01
【问题描述】:
我正在使用相同的iframe 在各种不同的站点上使用 python 运行 selenium 脚本。在某些站点上,我能够成功运行完整的代码,但是我遇到了一个站点,我在 iframe 中运行相同的代码,但收到一个错误,提示它无法找到该元素。
我尝试了不同的选择器,但同样的错误仍然存在。请记住,相同的代码可以在具有相同 iframe 的其他网站上成功运行。
这是iframe的html结构:
<iframe class="zoid-component-frame zoid-visible" frameborder="0" allowtransparency="true" name="xcomponent__div_renderer__latest__pmrhk2leei5cendcgi..." title="ShopRunner Love it. Get it." scrolling="no" style="background-color: transparent;" src="https://content.shoprunner.com/components/divRenderer/index.html?env=prd&uid=b9695b75b4&logLevel=error&version=latest&xcomponent=1"></iframe>
这里是按钮的结构:
<button aria-label="Sign up free for ShopRunner." class="sr-button bn bg-transparent underline ph0" type="button" data-trigger="learnMore">Sign Up FREE</button>
这是在其他网站上运行的代码版本:
# switch to the context of the browser
browser.switch_to.default_content()
# wait until iframe loads and then switch to the context of the iframe
browser.switch_to.frame(browser.find_element_by_class_name('zoid-component-frame'))
# wait for the learn more button to be clickable and then click
browser.find_element_by_css_selector("button[data-trigger='learnMore']").click()
# switch to the context of the modal
browser.switch_to.default_content()
# pause on learn more modal (for visual inspection) and then close modal
time.sleep(2)
browser.find_element_by_id('sr_header_close').click()
这些是我尝试过的其他一些选择器,但出现了同样的错误:
browser.find_element_by_xpath("//*[contains(text(), 'Sign Up FREE')]").click()
browser.find_element_by_css_selector(".sr-button.bn.bg-transparent.underline.ph0").click()
我还尝试在切换到 iframe 和查找 css 选择器之间添加等待语句,并尝试使用 ActionChain 来查找元素:
button = browser.find_element_by_css_selector("button[data-trigger='learnMore']")
browser.implicitly_wait(10)
ActionChains(browser).move_to_element(button).click(button).perform()
我希望能够点击按钮,但收到以下错误:
selenium.common.exceptions.NoSuchElementException:消息:没有这样的元素:无法找到元素:{"method":"css selector","selector":"button[data-trigger='learnMore']"}
【问题讨论】:
-
所有网站上的 iframe 类名称是否相同?看起来您在切换到 iframe 时没有使用完整的类名 - 'zoid-component-frame zoid-visible'。
-
你说得对,我只使用了部分名称,在其他站点上它是成功的,而在这个站点上它直到找到 iframe 后才会中断,只是有一些东西阻止它是在我还没有弄清楚的切换到 iframe 后找到元素。
标签: python selenium iframe browserstack