我正在尝试使用 Python-selenium 从 iframe 元素中的“src”中提取链接

这是 HTML

<div class="bg_tv col-md-12 online">
   <iframe width="100%" height="460" src="https://www.youtube.com/embed/dtKciwk_si4" scrolling="OFF" frameborder="0" allowfullscreen=""></iframe></div>

我试过:

browser.find_element(By.TAG_NAME, "iframe").get_attribute("src")

但我得到了:

no such element: Unable to locate element: {"method":"css selector","selector":"iframe"}

然后我尝试了 XPATH:

browser.find_element(By.XPATH,"/html/body/div/div[3]/div/div[2]/div[1]/iframe").get_attribute("src")

但也无法找到元素错误。有什么帮助吗?


有只小跳蛙
浏览 105回答 2
2回答

慕工程0101907

像 selenium 这样的浏览器运行程序可能会很困难,因为运行程序可能会在首先加载页面的所有元素之前执行脚本。我会尝试首先添加等待元素。正如 python-selenium 文档提供的那样:https://selenium-python.readthedocs.io/waits.html#explicit-waitsfrom selenium import webdriverfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as ECdriver = webdriver.Firefox()driver.get("http://somedomain/url_that_delays_loading")try:&nbsp; &nbsp; element = WebDriverWait(driver, 10).until(&nbsp; &nbsp; &nbsp; &nbsp; EC.presence_of_element_located((By.TAG_NAME, "iframe"))&nbsp; &nbsp; )finally:&nbsp; &nbsp; driver.quit()如果您的元素正在浏览器上下文中加载,这应该会获取您的元素。

月关宝盒

要打印src属性的值,<iframe>您需要引发WebDriverWait ,并且visibility_of_element_located()可以使用以下任一定位器策略:使用XPATH:print(WebDriverWait(browser, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='bg_tv col-md-12 online']/iframe[@src]"))).get_attribute("src"))使用CSS_SELECTOR:print(WebDriverWait(browser, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.bg_tv.col-md-12.online > iframe[src]"))).get_attribute("src"))注意:您必须添加以下导入:from selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support import expected_conditions as EC
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python