I'm new about using python and selenium and I'm trying to get the image source from a website. I'm actually finding elements by the tag name, but I don't know if it's the right way. Anyway it gives me an error:
InvalidArgumentException: Message: invalid argument: 'using' must be a string
Under this there's the code I wrote
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()
The error is in:
tag = driver.find_element((By.TAG_NAME, "b")).getText()
You can personally inspect the website because I really don't know how to solve this Every type of help is appreciated :)
CodePudding user response:
tag = driver.find_element((By.CSS_SELECTOR, "body > center:nth-child(1) > p:nth-child(3) > a > img"))
You can grab this by css selector and then use
tag.get_attribute('src')
to get the src image value.
CodePudding user response:
The image source is within an <iframe>
so you have to:
Induce WebDriverWait for the desired frame to be available and switch to it.
Induce WebDriverWait for the desired element to be clickable.
You can use the following Locator Strategies:
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"))
Console Output:
https://apod.nasa.gov/apod/image/2111/MACSJ0138_Hubble_1080.jpg
Note : You have to add the following imports :
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC
Reference
You can find a couple of relevant discussions in:
- Ways to deal with #document under iframe
- Switch to an iframe through Selenium and python
- selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element while trying to click Next button with selenium
- selenium in python : NoSuchElementException: Message: no such element: Unable to locate element