【问题标题】:Unable to switch iframe with src python selenium无法使用 src python selenium 切换 iframe
【发布时间】:2020-09-15 11:35:01
【问题描述】:

我无法在自动化代码中切换 iframe(我必须使用 python、selenium 从 kaggle 下载数据集)。这个 iframe 没有 id,也没有名字,只有 src。

我附上了 iframe HTML 的图片,否则看起来像这样:

> <iframe height="0" width="0" tabindex="-1"
> src="https://accounts.youtube.com/accounts/CheckConnection?pmpo=https%3A%2F%2Faccounts.google.com&amp;v=-1287755822&amp;timestamp=1600168651416"
> style="position: absolute; left: 0px; top: 0px; z-index:
> -1;"></iframe>

我的代码是:

def access_website():
   driver = webdriver.Chrome(ChromeDriverManager().install())
   driver.get('https://www.kaggle.com/c/titanic/data?select=train.csv')
   sleep(1)

   driver.find_element_by_xpath("/html/body/main/div[1]/div/div[6]/div/div[2]/div").click() #click new page
driver.find_element_by_xpath("/html/body/main/div[1]/div/div[5]/div[2]/div/div[2]/div[4]/div/div[1]/div[3]/button").click()#click download dataset

    #Google login appears 
    driver.switch_to.frame(driver.find_element_by_tag_name("iframe"))

代码返回:“消息:没有这样的元素:无法找到元素:{“method”:“xpath”,“selector”等”

enter image description here

【问题讨论】:

    标签: python-3.x selenium selenium-webdriver selenium-chromedriver


    【解决方案1】:

    您使用以下 css 选择器来识别 iframe。

    driver.switch_to.frame(driver.find_element_by_css_selector("iframe[src^='https://accounts.youtube.com/accounts/']"))
    

    为了获得最佳实践,我建议使用WebDriverWait()

    WebDriverWait(driver,10).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe[src^='https://accounts.youtube.com/accounts/']")))
    

    您需要导入以下库。

    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    

    【讨论】:

    • 它似乎有效,但是当我尝试将 Xpath 复制到 send_keys 以获取电子邮件 + 密码时,同样的消息“消息:没有这样的元素:无法找到元素:{“方法”:” xpath","selector":"/html/body/" - Xpath 是动态变化的吗?
    • @BaptisteFernandez:这是另一个问题。我相信它解决了您最初的问题。但是,如果您可以发布用户名和密码字段的相关 HTML,那就太好了
    • 所以我尝试了两次,两次 HTML 和完整的 Xpath 都是一样的;所以虽然代码没有给出 WedDriverWait 的错误,但它仍然有问题吗? HTML 电子邮件输入为: Xpathcode /html/body/div[1]/ div[1]/div[2]/div/div[2]/div/div/div[2]/div/div[1]/div/form/span/section/div/div/div[1]/ div/div[1]/div/div[1]/输入
    • 值得一提的是,我通过 class_name ("whsOnd zHQkBf")、name ("identifier") 进行了尝试,但它不起作用::"消息:没有这样的元素:无法找到元素:{"方法":"css 选择器","selector":"[name="identifier"]"}"
    • 这很有趣,因为如果我使用 python 控制台以交互方式进行操作,并且在尝试失败后我复制粘贴网站链接来执行此操作: driver.get("accounts.google.com/o/oauth2/v2/auth/… etc etc) driver.find_element_by_xpath ("/html/body/div[1]/div[1]/div[2]/div/div[2]/div/div/div[2]/div/div[1]/div/form/span /section/div/div/div[1]/div/div[1]/div/div[1]/input").send_keys("hello") 然后它工作 - 所以它似乎仍然是一个框架问题
    猜你喜欢
    • 2021-06-19
    • 1970-01-01
    • 2017-05-06
    • 1970-01-01
    • 1970-01-01
    • 2022-10-22
    • 2017-12-24
    • 2014-06-11
    • 1970-01-01
    相关资源
    最近更新 更多