参数无效:'using' 必须是在 iframe 中提取图像源的字符串

Invalid argument: 'using' must be a string extracting image source within an iframe

我刚开始使用 python 和 selenium,我正在尝试从网站获取图像源。我实际上是通过标签名称查找元素,但我不知道这是否是正确的方法。 无论如何它给了我一个错误:

InvalidArgumentException: Message: invalid argument: 'using' must be a string

下面是我写的代码

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager

PATH = Service("/Users/fscozano/documenti/chromedriver-2.exe")

print("setup")
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
driver.get("https://apod.nasa.gov/apod/random_apod.html")

tag = driver.find_element((By.TAG_NAME, "b")).getText()

print(tag)

driver.quit()

错误在:

tag = driver.find_element((By.TAG_NAME, "b")).getText()

你可以亲自去网站看看,我实在不知道怎么解决 感谢各种类型的帮助:)

图像源在 <iframe> 内,因此您必须:

  • 诱导 WebDriverWait 所需的 帧可用并切换到它

  • 诱导 所需的 元素可点击

  • 您可以使用以下:

    driver.get("https://apod.nasa.gov/apod/random_apod.html")
    WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe[src^='https://apod.nasa.gov/apod']")))
    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//h1[normalize-space()='Astronomy Picture of the Day']//following::p[2]//a/img"))).get_attribute("src"))
    
  • 控制台输出:

    https://apod.nasa.gov/apod/image/2111/MACSJ0138_Hubble_1080.jpg
    
  • 注意:您必须添加以下导入:

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

参考

您可以在以下位置找到一些相关讨论:

  • Switch to an iframe through Selenium and python