【问题标题】:Python Selenium driver.find_element_by_xpath can't find element within iframePython Selenium driver.find_element_by_xpath 在 iframe 中找不到元素
【发布时间】:2021-06-12 05:24:25
【问题描述】:

我正在尝试抓取一个网站以获取体育统计数据,并意识到所有重要数据都在 iframe 中。我使用 driver.switch_to.frame() 切换到 iframe 并且不会引发任何错误。

frame1 = '//iframe[@src="reallylongsource"]'


 driver.switch_to.frame(driver.find_element_by_xpath(frame1))

但是当我尝试访问 iframe 中的信息时,

selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: .//div[@class="classname"]

被提出。我可以看到该元素在 HTML 中,但我无法用 selenium 找到它。我也尝试使用 CSS 选择器定位它,但没有成功。

我很确定它也是正确的 iframe。我尝试使用 xpath 和标签名称找到它,它们是相同的 iframe。

当我打印时

print(driver.find_element_by_xpath(frame1).text)

我只得到空格

我已经把头撞在墙上很久了,我想不通!

似乎我能够切换到正确的 iframe,但 selenium 在其中找不到任何信息。

【问题讨论】:

  • 使用 document.getElementById('iframe_id').contentWindow.document.body.innerHTML; 从浏览器检查检查元素控制台,其中 iframe_id 是您的 ID,以检查您是否获得内容。
  • 你能分享那个 iframe 所在的链接吗?页面上是否有超过 1 个 iframe?如果没有,请尝试通过 drive.switch_to.frame(driver.find_element_by_tag_name('iframe')) 查找
  • @Xitrex,看起来像是带有选择器的东西..
  • 不要使用 .它仅适用于子 xpath。
  • 这里是页面链接:campobet.se/en/sport/prelive?sportids=66我的目标是能够选择一个游戏并继续到列出投注的页面并收集有关赔率的信息

标签: python html selenium iframe


【解决方案1】:

尝试这样使用:

driver = webdriver.Chrome()
driver.get(URL)

driver.implicitly_wait(5)

driver.switch_to.frame(driver.find_element(By.TAG_NAME, 'iframe'))

element = driver.find_element(By.XPATH, '//div[@class="classname"]')

driver.quit()

如果与您在代码中所做的相同,请提供更多信息以查看该页面

试试这个,它会移动到第一类游戏的第一个游戏,得到所有的分数并打印出来:

import time

from selenium import webdriver

driver = webdriver.Chrome()

driver.get('https://campobet.se/en/sport/prelive?sportids=66')
time.sleep(5)

driver.switch_to.frame(
    driver.find_element_by_xpath("//iframe[contains(@src, 'https://sb1client-altenar.biahosted.com')]"))
time.sleep(1)

game_types = driver.find_elements_by_xpath("//div[@name='leagues-selector']")
time.sleep(1)
game_types[0].click()
time.sleep(1)
games = driver.find_elements_by_xpath(
    "//div[@class='_asb_simple-button _asb_simple-button-pointer  _asb_leagues-selector-item ']")
games[0].click()
time.sleep(1)
scores = driver.find_elements_by_xpath("//div[@class='asb-flex-cc asb-unshrink _asb_price-block-content-price ']/span")
time.sleep(1)

scores_values = [el.text for el in scores]
time.sleep(1)
print(scores_values)
driver.quit()

【讨论】:

  • 不幸的是,这正是我正在做的事情。这是页面的链接:campobet.se/en/sport/prelive?sportids=66 我的目标是能够选择一个游戏,进入它的页面并为我的朋友收集有关 E 的所有可用赔率的信息-体育博彩
  • 谢谢,是的,那部分我写得不好。我只需要有关如何访问 iframe 中的信息的帮助,以便我的代码可以处理它。其余的我想自己弄清楚!
  • 看来我可以切换到正确的 iframe 但 selenium 似乎无法在其中找到任何信息。我的问题是为什么会这样,或者我如何帮助我的代码在 iframe 中找到我要查找的内容。
  • @Xitrex 等一下,我会发布解决方案
  • @Xitrex 看看
猜你喜欢
  • 2021-12-30
  • 2016-05-28
  • 2020-04-12
  • 1970-01-01
  • 1970-01-01
  • 2021-08-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多